PHP 8.1.31 Released!

array_find

(PHP 8 >= 8.4.0)

array_findReturns the first element satisfying a callback function

说明

array_find(array $array, callable $callback): mixed

array_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
The array that should be searched.
callback

The callback function to call to check each element, which must be

callback(mixed $value, mixed $key): bool
If this function returns true, 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.

示例

示例 #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);
}));
?>

以上示例会输出:

string(5) "goose"
NULL
string(3) "cow"
string(3) "dog"

参见

  • array_find_key() - Returns the key of the first element satisfying a callback function
  • array_all() - Checks if all array elements satisfy a callback function
  • array_any() - Checks if at least one array element satisfies a callback function
  • array_filter() - 使用回调函数过滤数组的元素
  • array_reduce() - 用回调函数迭代地将数组简化为单一的值
添加备注

用户贡献的备注

此页面尚无用户贡献的备注。
To Top