ZetCode

PHP array_all 函数

最后修改于 2025 年 3 月 13 日

PHP array_all 函数检查数组中的所有元素是否通过由回调函数实现的测试。它对验证很有用。

基本定义

array_all 函数测试所有元素是否满足某个条件。如果所有元素都通过测试,则返回 true,否则返回 false。

语法:array_all(array $array, callable $callback): bool。回调函数应该对通过的元素返回 true。空数组返回 true。

基本的 array_all 示例

这显示了对所有数组元素都是正数的简单验证。

basic_array_all.php
<?php

declare(strict_types=1);

function array_all(array $array, callable $callback): bool {
    foreach ($array as $element) {
        if (!$callback($element)) {
            return false;
        }
    }
    return true;
}

$numbers = [2, 4, 6, 8];
$allEven = array_all($numbers, fn($n): bool => $n % 2 === 0);

echo $allEven ? 'All even' : 'Not all even'; 

这检查所有数字是否为偶数。回调函数测试每个元素,并且由于所有元素都通过测试,因此 array_all 返回 true。

验证字符串长度

检查数组中的所有字符串是否满足最小长度要求。

string_lengths.php
<?php

declare(strict_types=1);

$names = ["Alice", "Bob", "Charlie"];
$allLongEnough = array_all($names, fn($name): bool => strlen($name) >= 3);

echo $allLongEnough ? 'All valid' : 'Some too short'; 

这验证所有名称至少有 3 个字符。 回调函数检查字符串长度,在这种情况下,对所有元素返回 true。

对象属性验证

验证数组中的所有对象是否具有满足条件的属性。

object_validation.php
<?php

declare(strict_types=1);

class Product {
    public function __construct(
        public string $name,
        public float $price
    ) {}
}

$products = [
    new Product("Laptop", 999.99),
    new Product("Phone", 699.99),
    new Product("Tablet", 399.99)
];

$allExpensive = array_all($products, fn(Product $p): bool => $p->price > 300);

echo $allExpensive ? 'All expensive' : 'Some cheap'; 

这检查所有产品的价格是否超过 300。 回调函数检查每个对象的 price 属性,对此数据集返回 true。

空数组行为

array_all 对空数组返回 true,这可能很有用。

empty_array.php
<?php

declare(strict_types=1);

$emptyArray = [];
$result = array_all($emptyArray, fn($x): bool => $x > 10);

echo $result ? 'All pass (vacuous truth)' : 'Some fail'; 

由于没有元素要检查,array_all 返回 true。 这遵循数学逻辑,即对空集的普遍量化为真。

提前终止

array_all 在第一次失败后停止检查以提高效率。

early_termination.php
<?php

declare(strict_types=1);

$numbers = [2, 4, 5, 8];
$allEven = array_all($numbers, function($n): bool {
    echo "Checking $n\n";
    return $n % 2 === 0;
});

echo $allEven ? 'All even' : 'Not all even'; 

该函数在第一个奇数 (5) 处停止。 您将只看到 2、4 和 5 的输出,这演示了短路行为。

最佳实践

来源

PHP Array Filter 文档(相关功能)

本教程涵盖了 PHP array_all 模式,并提供了实际示例,展示了它在数组验证场景中的用法。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 数组函数