search

Home  >  Q&A  >  body text

Logical operators and assignment operator precedence in PHP.

<p>I recently found it in a passage like this:</p> <pre class="brush:php;toolbar:false;">$x = 2 && $y = 3; echo (int)$x.':'.(int)$y;</ pre> <p>This code snippet produces output 1:3. By looking at the operator precedence table, I found that the logical operators || and && have higher precedence than the assignment operator =. Therefore, the first expression should be treated as $x = ($y || 2) = 3; which makes $x = (2 && $y) = 3; and finally evaluates to $x = false = 3;. Second, the assignment operator has right-ordering, so the interpreter should try to do false = 3, which is obviously illegal. So, in my opinion, the above mentioned code snippet should fail to compile and should throw a parse or runtime error. But instead, this snippet produced 1:3. This means that what the interpreter does is: </p> <blockquote> <p>a) $y=3</p> <p>b) 2 && $y</p> <p>c) $x = (2 && $y)</p> </blockquote> <p>Why do this instead of based on operator precedence?</p>
P粉176980522P粉176980522508 days ago572

reply all(1)I'll reply

  • P粉615829742

    P粉6158297422023-08-08 00:02:37

    The operator precedence table you provided states as a separate comment:

    So, in effect, the assignment within the expression will be treated as a subexpression. How and when this is done is not clearly stated in the documentation, which simply states that "similar" expressions will work this way.

    reply
    0
  • Cancelreply