PHP 8.4 array_find() and array_find_key() — replacing the old filter pattern
PHP 8.4 added array_find() and array_find_key() and I keep seeing people still use the old array_filter + array_values combination that returns an array when they only need one element.
Run this in the sandbox to compare both approaches:
The old pattern allocates a new array for something you throw away immediately. array_find() stops at the first match, so it is faster on large arrays too.
Good catch. Worth noting that array_find() uses the same short-circuit behavior as a foreach with break. I benchmarked it against the filter approach on an array of 100k elements where the match is at index 500: array_find() is about 180x faster in that case because it stops immediately.
Here is the benchmark you can run yourself:
One edge case to be aware of: array_find() returns null both when nothing is found and when the matching element itself is null. If you store nulls in your array you need a different check.
This is the same ambiguity as array_search() returning false vs 0. Use array_find_key() when the value might be null.
```php blocks are runnable.