PHP Reference ยท Array Functions
PHP array_find(), array_any() and array_all() functions
Reference for PHP 8.4 array_find(), array_find_key(), array_any() and array_all(): search an array with a callback and test conditions on its elements.
PHP 8.4 added four small functions that take a callback and answer common questions about an array. array_find() returns the first value for which the callback returns true, and array_find_key() returns its key. array_any() says whether at least one element passes, and array_all() says whether every element passes.
They stop as soon as the answer is known, so they are faster than array_filter() when you only need one result. They exist in PHP 8.4 and later only.
<?php $found = array_find([3, 8, 12], fn($n) => $n > 5); // 8
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_find(array $array, callable $callback): mixed array_find_key(array $array, callable $callback): mixed array_any(array $array, callable $callback): bool array_all(array $array, callable $callback): bool
| Name | Description |
|---|---|
$array |
The array to search. |
$callback |
Called as callback($value, $key). Its return value is treated as true or false. |
Return value: array_find() returns the first matching value or null; array_find_key() returns the first matching key or null; array_any() and array_all() return bool.
Usage notes
- Order: elements are checked in array order, and checking stops at the first decisive element.
nullis ambiguous. Anullfromarray_find()could mean "no match" or "the match is the valuenull". Usearray_find_key()orarray_any()if that matters.- Empty arrays:
array_any()returnsfalse, andarray_all()returnstrue(nothing fails). - Not like
array_filter(): there the callback gets only the value unless you ask for the key with a mode flag. Here it always gets($value, $key). - Before PHP 8.4, use a
foreachwithreturn, orarray_filter()andreset(). - Compared with
in_array()andarray_search(), these accept any condition, not just equality.