Array AND ()? Logical designation of all elements

I have an array and I want to find out if there is at least one false value in it. I was thinking of creating an array_and() function that just performs a logical AND for all elements. It will return true if all values โ€‹โ€‹are true, otherwise false. Am I redoing?

+7
arrays php boolean-logic
source share
6 answers

Why are you just not using

  • in_array - Checks if a value exists in an array

Example:

 // creates an array with 10 booleans having the value true. $array = array_fill(0, 10, TRUE); // checking if it contains a boolean false var_dump(in_array(FALSE, $array, TRUE)); // FALSE // adding a boolean with the value false to the array $array[] = FALSE; // checking if it contains a boolean false now var_dump(in_array(FALSE, $array, TRUE)); // TRUE 
+11
source share

It will return true if all values โ€‹โ€‹are true, otherwise false.

Returns true if the array is not empty and does not contain false elements:

 function array_and(arary $arr) { return $arr && array_reduce($arr, function($a, $b) { return $a && $b; }, true)); } 

(Note that you need a strict comparison if you want to test it with type false .)

Can i overestimate

Yes, because you could use:

 in_array(false, $arr, true); 
+3
source share

There is nothing wrong with this, in principle, if you do not. And all the values โ€‹โ€‹indiscriminately; that is, you should stop working as soon as the first false is found:

 function array_and(array $array) { foreach ($array as $value) { if (!$value) { return false; } } return true; } 
+1
source share

you should be able to implement a small function that takes an array and iterates over it, checking each element to determine if it is false. Return bool from a function based on the results of your check ....

0
source share

Easy but ugly => O (N)

 $a = array(1, 2, false, 5, 6, 'a'); $_there_is_a_false = false foreach ($a as $b) { $_there_is_a_false = !$b ? true : $_there_is_a_false; } 

another option: array-filter

0
source share

Why not just use array_product ()

$ set = array (1,1,1,1,0,0);

$ result = array_product ($ set);

Output: 0

And logic is essentially a factor.

1 * 1 = 1

1 * 0 = 0

0 * 1 = 0

0 * 0 = 0

0
source share

All Articles