在所有数组的布尔元素上使用`或`或`和`运算符并返回结果

时间:2014-03-13 11:34:35

标签: php

我们说我们有一个阵列:

$input = [true, false, false, true, true];

我需要的是在所有数组元素上返回orand操作的布尔结果,所以:

and($input); // false
or($input);  // true

我正在寻找内置的东西 - 而不是循环或求和项目的解决方案。

即。无效的方法:

array_sum($input) > 0;

2 个答案:

答案 0 :(得分:3)

$or  = array_reduce($input, function ($result, $item) { return $result || $item; }, false);
$and = array_reduce($input, function ($result, $item) { return $result && $item; }, true);

这就像“内置”一样。

答案 1 :(得分:1)

“或”可由array_filter完成,无需回调:

$result_of_or = array_filter($input);
// result will be truthy if at least one element is true
// otherwise, result is empty array, which is falsy

“和”是一个小问题,但可以这样做:

$result_of_and = count(array_filter($input)) == count($input);

基本上它会删除任何有价值的值,然后确定是否删除了任何元素 - 如果没有,则它们都是真的。