PHP 8.6.0 Alpha 2 available for testing

array_find

(PHP 8 >= 8.4.0)

array_find返回满足回调函数条件的第一个元素

说明

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

array_find() 返回 array 中第一个使指定 callback 返回 true 的元素的值。如果未找到匹配的元素,则该函数返回 null

参数

array
需要被遍历的 array
callback

用于检查每个元素的回调函数,该函数必须

function callback(mixed $value, mixed $key): bool
如果该回调函数返回 truearray_find() 就会返回对应元素的值,并且不再对后续元素执行该回调。

返回值

该函数返回第一个使 callback 返回 true 的元素的值。如果未找到匹配的元素,则函数返回 null

示例

示例 #1 array_find() 示例

<?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() - 返回满足回调函数条件的第一个元素的键
  • array_all() - 检查数组所有元素是否都满足回调函数的条件
  • array_any() - 检查数组中是否至少有一个元素满足回调函数的条件
  • array_filter() - 使用回调函数过滤数组的元素
  • array_reduce() - 用回调函数迭代地将数组简化为单一的值
添加备注

用户贡献的备注 2 notes

up
14
mail at nititech dot de
1 year ago
A simple fallback For older PHP versions, that do not have array_find:

<?php

/**
 * Porting of PHP 8.4 function
 *
 * @template TValue of mixed
 * @template TKey of array-key
 *
 * @param array<TKey, TValue> $array
 * @param callable(TValue $value, TKey $key): bool $callback
 * @return ?TValue
 *
 * @see https://www.php.net/manual/en/function.array-find.php
 */
function array_find(array $array, callable $callback): mixed
{
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            return $value;
        }
    }

    return null;
}
?>
up
0
harl at gmail dot com
8 months ago
Note that if null satisfies the callback then there is no way to tell if null was returned because it was found in the array or if it was because nothing satisfying the callback was found.

In this case, it'll be more robust to use array_find_key; null can't be a key, so if that's what you get it must be because the search failed to find a match.

Obviously, you'd then use the array key to look up the corresponding value in the array.
To Top