Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 513
user151841 Avatar asked Nov 30 '10 19:11

user151841


3 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
like image 128
Gordon Avatar answered Sep 22 '22 18:09

Gordon


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);
like image 33
Matthew Avatar answered Sep 21 '22 18:09

Matthew


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;
}
like image 26
Will Vousden Avatar answered Sep 21 '22 18:09

Will Vousden