Search code examples
phpoperator-precedenceassociativity

How is "$foo = 5 && $bar = 15" evaluated, and why is it not a error?


Let's say we got a simple code like this:

// $foo and $bar aren't defined before

$foo = 5 && $bar = 15;

// var_dump()
// $foo is (bool) TRUE
// $bar is (int) 15

so I assume it works like:

$foo = (5 && ($bar = 15))

but in my opinion it should be:

$foo = ((5 && $bar) = 15) // should throw syntax error due FALSE = 15
  1. evaluation form left to right [$foo want 5 but && is higher]
  2. && got the highest priority [so && takes 5 and $bar]
    • 5 == TRUE; $bar == Undefined [so it's NULL == FALSE]
  3. = got the right associativity [waits for evaluation of (5 && $bar)]

Please explain it in easiest way (on some other examples) to poor man like me. Regards.


Solution

  • I think reading the manual page here helps and clears a lot of things.

    So how does this get's evaluated?

    $foo = 5 && $bar = 15;
    

    First you have to know that && has a higher precedence than =. So the first thought would be this:

    $foo = (5 && $bar) = 15;
    

    But now is the point where you have to read the manual until the end: http://php.net/manual/en/language.operators.precedence.php

    And a quote from there:

    Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.

    What does that mean?

    It silently assign 15 to $bar e.g.

    $foo = (5 && ($bar = 15));
    

    Now you can evaluate &&, $bar get's assigned with 15 and 5 && 15 is TRUE and get's assign to $foo