(PHP 8 >= 8.4.0)
array_find — Returns the first element satisfying a callback function
Descriptionarray_find() returns the value of the first element of an array for which the given callback
returns true
. If no matching element is found the function returns null
.
array
callback
The callback function to call to check each element, which must be
If this function returnstrue
, the value is returned from array_find() and the callback will not be called for further elements.
The function returns the value of the first element for which the callback
returns true
. If no matching element is found the function returns null
.
Example #1 array_find() example
<?php
$array = [
'a' => 'dog',
'b' => 'cat',
'c' => 'cow',
'd' => 'duck',
'e' => 'goose',
'f' => 'elephant'
];// Find the first animal with a name longer than 4 characters.
var_dump(array_find($array, function (string $value) {
return strlen($value) > 4;
}));// Find the first animal whose name begins with f.
var_dump(array_find($array, function (string $value) {
return str_starts_with($value, 'f');
}));// Find the first animal where the array key is the first symbol of the animal.
var_dump(array_find($array, function (string $value, $key) {
return $value[0] === $key;
}));// Find the first animal where the array key matching a RegEx.
var_dump(array_find($array, function ($value, $key) {
return preg_match('/^([a-f])$/', $key);
}));
?>
The above example will output:
string(5) "goose" NULL string(3) "cow" string(3) "dog"See Also
3 months ago
A simple fallback For older PHP versions, that do not have array_find:
<?php function array_find(array $array, callable $callback): mixed
{
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return $value;
}
}
return
null;
}
?>
↑ and ↓ to navigate • Enter to select • Esc to close
Press Enter without selection to search using Google
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4