Search code examples
phpbooleanoperator-precedence

PHP precedence of operators


I read that = has a higher precedence than and

Let's say you got

$boolone = true;
$booltwo= false;
$res = $boolone and $booltwo;

I had guessed this would turn false since $res = true and false where true and false equals to false. But since = has higher precedence it's supposed to turn true. Which is like this

($res = $boolone) and $booltwo;

This returns true but my question is why does it return true, shouldn't it return false? Since $res = $booloneequals trueand $booltwois false by default, so we have this: true and false which should normally return false, but again, why true?

Simply said:

($res = $boolone) and $booltwo;
(true) and false; //returns true?

Solution

  • You're correct that

    $res = $boolone and $booltwo;
    

    is equivalent to

    ($res = $boolone) and $booltwo;
    

    Because of operator precedence,

    $res = $boolone
    

    is evaluated first, with the value of $boolone being assigned to $res....

    $booltwo is then anded with the result of that first evaluation result (true and false), but you're doing nothing with that evaluation, so it is simply discarded... it isn't assigned to $res, because that assignment has already been completed by the first evaluation.

    If you do

    var_dump($res = $boolone and $booltwo);
    

    then you'll see the result of the full evaluation that is discarded, and $res is still true