Search code examples
phpoperator-precedence

Operator Precedence in PHP: Ternary XOR Assignment


After writing my response on the question how to assign to multiple variables in a ternary operator I actually tried out the code I wrote:

true ? $w = 100 xor $r = 200 : $w = 300 xor $r = 400;
var_dump($w); var_dump($r);

(Don't bother it's useless, this is theoretic.)

Now, I would expect PHP to do it this way, according to operator precedence:

 true  ?   $w = 100  xor  $r = 200   :   $w = 300  xor  $r = 400  ;
(true) ? ( $w = 100  xor  $r = 200 ) : ( $w = 300  xor  $r = 400 );
(true) ? (($w = 100) xor ($r = 200)) : (($w = 300) xor ($r = 400));

As the first part of the ternary operator is evaluated, this should output:

int 100
int 200

But instead I get

int 100
int 400

This is very odd to me, because it would require that parts of both parts of the ternary operator are executed.

Suppose it's some fault in my thinking.


Solution

  • aren't you just doing

    (true ? $w = 100 xor $r = 200 : $w = 300) xor $r = 400;