Reputation: 152236
Let's say we have an array:
$input = [true, false, false, true, true];
What I need is to return a boolean result of or
or and
operation on all array's elements, so:
and($input); // false
or($input); // true
I am looking for something built-in - not solutions with looping or summing items.
I.e. invalid method:
array_sum($input) > 0;
Upvotes: 0
Views: 194
Reputation: 522185
$or = array_reduce($input, function ($result, $item) { return $result || $item; }, false);
$and = array_reduce($input, function ($result, $item) { return $result && $item; }, true);
That's about as "built-in" as it gets.
Upvotes: 3
Reputation: 324650
"or" can be fulfilled by array_filter
without a callback:
$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
"and" is a little tricker, but could be done like this:
$result_of_and = count(array_filter($input)) == count($input);
Essentially it removes any falsy values, and then determines if any elements were removed - if none were, then they were all true.
Upvotes: 1