PHP 8.5.8 Released!

array_any

(PHP 8 >= 8.4.0)

array_anyChecks if at least one array element satisfies a callback function

说明

function array_any(array $array, callable $callback): bool

array_any() returns true , if the given callback returns true for any element. Otherwise the function returns false .

参数

array
The array that should be searched.
callback

The callback function to call to check each element, which must be of the following signature:

function callback(mixed $value, mixed $key): bool
If this function returns true , true is returned from array_any() and the callback will not be called for further elements.

返回值

The function returns true , if there is at least one element for which callback returns true . Otherwise the function returns false .

示例

示例 #1 array_any() example

<?php
$array = [
 'a' => 'dog',
 'b' => 'cat',
 'c' => 'cow',
 'd' => 'duck',
 'e' => 'goose',
 'f' => 'elephant'
];
// Check, if any animal name is longer than 5 letters.
var_dump(array_any($array, function (string $value) {
 return strlen($value) > 5;
}));
// Check, if any animal name is shorter than 3 letters.
var_dump(array_any($array, function (string $value) {
 return strlen($value) < 3;
}));
// Check, if any array key is not a string.
var_dump(array_any($array, function (string $value, $key) {
 return !is_string($key);
}));
?>

以上示例会输出:

bool(true)
bool(false)
bool(false)

参见

  • array_all() - 检查数组所有元素是否都满足回调函数的条件
  • array_filter() - 使用回调函数过滤数组的元素
  • array_find() - Returns the first element satisfying a callback function
  • array_find_key() - Returns the key of the first element satisfying a callback function

发现了问题?

了解如何改进此页面提交拉取请求报告一个错误
+添加备注

用户贡献的备注 1 note

up
0
miken32 at example dot com
9 months ago
This can be a replacement for array_filter() where an existence check is the only purpose. But, unlike array_filter(), the callback always requires two arguments. There's no way to change this, so some a lot of old-fashioned string callables are no longer usable.
<?php
$arr = [45, 'abc', 'def', 'ghi'];
if (array_filter($arr, 'is_integer')) {
 // works because of loose comparison: [45] == true
}
if (array_any($arr, 'is_integer')) {
 // PHP Warning: Uncaught ArgumentCountError: is_integer() expects exactly 1 argument, 2 given
}
?>
+添加备注

AltStyle によって変換されたページ (->オリジナル) /