array_find() Function In PHP

PHP does not have a built in function named array_find(). To find the first array element that matches a condition, use array_find() in PHP 8.4 and later. It returns the matching value, or null if no element matches. The callback receives each value, its key, and the array.

Version Support: array_find() in PHP 8.5, array_find() in PHP 8.4, array_find() in PHP 8.3, array_find() in PHP 8.2, array_find() in PHP 8.1, array_find() in PHP 7.1, array_find() in PHP 7.2, array_find() in PHP 7.3, array_find() in PHP 7.4

<?php
$numbers = [3, 8, 11, 14, 17];

$found = array_find($numbers, function ($number) {
   return $number > 10;
});

var_dump($found); // int(11) 

?>

The search stops at the first match, so this example returns 11, not 14 or 17.

You can also use an arrow function:

<?php

$words = ["pear", "banana", "plum"];

$longWord = array_find(
   $words,
   fn($word) => strlen($word) > 5
);

var_dump($longWord); // string(6) “banana”

?>

For associative arrays, the callback can inspect the key:

<?php

$users = [
   "u1" => ["name" => "Mia", "active" => false],
   "u2" => ["name" => "Noah", "active" => true],
];

$activeUser = array_find(
   $users,
   fn($user) => $user["active"]
);

print_r($activeUser); // ["name" => "Noah", "active" => true]

?>

If no element satisfies the condition, array_find() returns null. This can be ambiguous if null itself is a valid matching value, so consider checking with array_find_key() when you need to distinguish “not found” from a matched null. On PHP versions before 8.4, use a foreach loop or write a small helper function.

19 Views