Logical Operators and Precedence

61 views Asked by At

So I just did some random test and understand the fundamentals of Precedence and the || and or operators but I'm having trouble understanding why $f changes:

$f = 0 || 1;

if ($f === 1){
    echo "TRUE - $f";
}else{ 
   echo "FALSE - $f";
}
$f = 0 or 1;

if ($f === 0){
    echo "TRUE - $f";
}else{ 
   echo "FALSE - $f";
}

Thanks for some insight.

3

There are 3 answers

6
BlackM On BEST ANSWER

It's normal to evaluate always to True. The reason is that OR means if that one of the values is True it will take this one.

Update to your new question:

The answer is that "||" has a greater precedence than "or"

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;

You can learn more at the PHP manual website here which I found this example

0
PEM On

What you are doing is the same as :

if (($f = 0) or 1){ 
    // $f is being assigned the value 0, and the condition evaluates 0 or 1,
    // 1 being equivalent to true, the condition is always true.
    echo "TRUE - $f";
}else{
    echo "FALSE - $f";
}

and

if ($f = (0 || 1)){ // which gives $f = true which returns true
    echo "TRUE - $f";
}else{
    echo "FALSE - $f";
}

if you want to check if $f is equal to a value or another you would do

if ($f === 0 or $f === 1)

Be aware that in php, by default an int 1 will be evaluated to bool true unless you do a strict comparison === or !==

0
Farcas Cristian On

the problem is here: "if ($f = 0 or 1){" :

"=" means you give the variable $f the value 0

You should use :

  • "==" : checks if the values are equal
  • "===" : checks if the left variable is identical to the right variable (value, type, etc.)