New Array Search Functions in PHP 8.4: array_find, array_find_key, and array_find_index
PHP 8.4 introduces three powerful array‑search functions—array_find, array_find_key, and array_find_index—that let developers locate elements or keys based on custom callbacks, improving code readability, efficiency, and maintainability when working with complex arrays.
PHP 8.4 brings a set of new array‑search functions that greatly enhance the way developers work with arrays. The three functions— array_find() , array_find_key() , and array_find_index() —allow you to search an array using a user‑defined callback and return the first matching element, its key, or its numeric index.
array_find()
This function iterates over an array and returns the first element that satisfies the condition defined in the callback. Its signature is:
array_find(array $array, callable $callback): mixedThe $array parameter is the array to search, and $callback should return true for the desired element. If a matching element is found, its value is returned; otherwise null , false , or another implementation‑specific value may be returned.
Example:
$numbers = [1, 2, 3, 4, 5];
$result = array_find($numbers, function($value) {
return $value > 3;
});
echo $result; // outputs: 4array_find_key()
This function searches an array and returns the key of the first element that meets the callback condition. Its signature is:
array_find_key(array $array, callable $callback): int|string|nullIf a matching element is found, the key (integer or string) is returned; otherwise null is returned. The callback must return a boolean.
Example:
$users = [
'john' => ['age' => 25],
'jane' => ['age' => 30],
'doe' => ['age' => 35],
];
$key = array_find_key($users, function($user) {
return $user['age'] > 28;
});
echo $key; // outputs: janearray_find_index()
This function is similar to array_find_key() but returns the numeric index of the first element that satisfies the callback. Its signature is:
array_find_index(array $array, callable $callback): int|nullIf a matching element is found, its integer index is returned; otherwise null is returned.
Example:
$colors = ['red', 'green', 'blue', 'yellow'];
$index = array_find_index($colors, function($color) {
return $color === 'blue';
});
echo $index; // outputs: 2These new functions simplify custom array searches, make code more expressive, and improve maintainability in PHP web development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.