In PHP, array_find() returns the first value in an array for which a callback function returns true. It stops searching as soon as it finds a match.
You use array_find() to pick one item from a list, such as the first number above a limit or the first active user. If nothing matches, it returns null. The callback gets the value first and the key second.
Syntax
Call array_find() with the values you need. Start with this line.
PHP
$first = array_find($numbers, fn($n) => $n > 6);
Call
What it does
array_find([3, 8, 5, 12], fn($n) => $n > 6)
Returns 8, the first number above 6.
array_find([1, 3, 5], fn($n) => $n % 2 === 0)
Returns null, because no number is even.
array_find($users, fn($u) => $u['active'])
Returns the first user whose 'active' field is true.
array_find() was added in PHP 8.4. If you need the key of the match and not the value, use array_find_key(). If you only need to know that a match exists, use array_any().
Each item in $users is a record, and the callback receives one record at a time.
Asha is not active, so the callback returns false for her record.
Ravi is the first active user, so array_find() returns his whole record.
Meena is also active, but the search had already stopped, so Ravi is returned.
Frequently Asked Questions
It returns the first value in an array for which a callback returns true. If no item matches, it returns null.
array_find() was added in PHP 8.4. On older versions you can use a foreach loop with a return or a polyfill.
Use array_find_key(). It runs the same kind of search but returns the key of the first match.
array_find() returns null in both cases. Use array_find_key(), which returns null only when nothing matched, or use array_any() first to check for a match.
array_filter() returns all matches as a new array. array_find() returns only the first match and stops looking after that.