hsz
hsz

Reputation: 152236

Use `or` or `and` operator on all array's boolean elements and return result

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

Answers (2)

deceze
deceze

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions