Home » Php » php – Array AND() ? Logical ANDing of all elements

php – Array AND() ? Logical ANDing of all elements

Posted by: admin July 12, 2020 Leave a comment

Questions:

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 on all the elements. It would return true if all values are true, otherwise false. Am I over-engineering?

How to&Answers:

Why dont you just use

  • 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

Answer:

It would return true if all values are true, otherwise false.

Returns true if array is non empty and contains no false elements:

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

(Note that you would need strict comparison if you wanted to test against the false type.)

Am I over-engineering?

Yes, because you could use:

in_array(false, $arr, true);

Answer:

There’s nothing wrong with this in principle, as long as you don’t AND all of the values indiscriminately; that is, you should terminate as soon as the first false is found:

function array_and(array $array)
{
    foreach ($array as $value)
    {
        if (!$value)
        {
            return false;
        }
    }

    return true;
}

Answer:

you should be able to implement a small function that takes an array and iterates over it checking each member to see if it is false. Return a bool from the function based on the outcome of your checking….

Answer:

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

Answer:

Why not just use array_product()

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

$result = array_product($set);

Output: 0

AND Logical is essentially a multiplier.

1 * 1 = 1

1 * 0 = 0

0 * 1 = 0

0 * 0 = 0