2

i have a problem with my function which should combine logical operators according to data in array:

$arr = array(
    0 => array(false, "or"),
    1 => array(false, "or"),
    2 => array(true)
);

the equation should be:

  • false or false or true
  • ($arr[0][0] $arr[0][1] $arr[1][0] $arr[1][1] $arr[2][0])

And the result: true

But something wrong happens in function and it returns false. What am i missing?

var_dump( arrayBoolValidation($arr) );

function arrayBoolValidation (array $arr) {
    $num = count($arr);
    $status = $arr[0][0];
    for($i = 1; $i < $num; ++$i) {
        if ($arr[$i-1][1] == "and") {
            $status = filter_var($status, FILTER_VALIDATE_BOOLEAN) and filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN);
        } else if ($arr[$i-1][1] == "or") {
            $status = filter_var($status, FILTER_VALIDATE_BOOLEAN) or filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN);
        }
    }
    return $status;
}
rokas
  • 1,521
  • 9
  • 16
  • Mikalkenas: Perhaps you should have a look at this: http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – MDChaara Jan 27 '16 at 10:02

4 Answers4

2

It's an operator precedence issue. and is not the same as &&. Look at http://php.net/manual/en/language.operators.precedence.php

= has higher priority than and, so $a = $b and $c; equals to $a = $b;.

You must use extra brackets ($a = ($b and $c);) or better use &&. Same thing about or (use ||).

ksimka
  • 1,394
  • 9
  • 21
0

Assuming that all conditions have to be evaluated:

Note: I have added the case when no operator is defined.

    [...]
    if (!isset($arr[$i-1][1])) {
        $status = $status || $arr[$i][0];  // default: OR, && else
    } else if ($arr[$i-1][1] == "and") {
        $status = $status && $arr[$i][0];
    } else if ($arr[$i-1][1] == "or") {
        $status = $status || $arr[$i][0];
    }
    [...]
hherger
  • 1,660
  • 1
  • 10
  • 13
0

Change the following inside your loop:

if ($arr[$i-1][1] == "and") {
    $status = (filter_var($status, FILTER_VALIDATE_BOOLEAN) and filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN));
} else if ($arr[$i-1][1] == "or") {
    $status = (filter_var($status, FILTER_VALIDATE_BOOLEAN) or filter_var($arr[$i][0], FILTER_VALIDATE_BOOLEAN));
}

You'll see the extra brackets.

If you don't put them, you set $status to filter_var($status, FILTER_VALIDATE_BOOLEAN), which will always be the same as the first entry (false in this case).

Blaatpraat
  • 2,829
  • 11
  • 23
-1

I think there is something wrong in loop

try,

for($i = 1; $i <=$num; ++$i) {
Shivanand
  • 11
  • 5