user151841
user151841

Reputation: 18046

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?

Upvotes: 7

Views: 2969

Answers (6)

Gordon
Gordon

Reputation: 317009

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

Upvotes: 12

mechimdi
mechimdi

Reputation: 328

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

Upvotes: 0

Gabriel Sosa
Gabriel Sosa

Reputation: 7956

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

Upvotes: 0

martynthewolf
martynthewolf

Reputation: 1708

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....

Upvotes: 0

Matthew
Matthew

Reputation: 48294

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);

Upvotes: 5

Will Vousden
Will Vousden

Reputation: 33358

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;
}

Upvotes: 1

Related Questions