How is ++$a + $a++ ambiguous in PHP? How is ++$a + $a++ ambiguous in PHP? php php

How is ++$a + $a++ ambiguous in PHP?


++$a let $a be 2, and return 2,$a++ increment $a again, so $a is 3 now, but it return 2.

In the same PHP version, the result is always same. But it may produce different result if PHP version changed. It depends on ++$a and $a++, which one is evaluated first. If $a++ is evaluated first, the result will be 5, otherwise the result will be 4.


Please note that this is just my humble opinion.

I think the idea beneath this result is that none of the aperands has precedence when there's a single operator and that in an operation a variable is kept as a reference instead of being replaced by its result during all the calculation until the last one (plus, in this example). So when it goes from l-r:

$a = 1;++$a + $a++operand 1 --> ++$a ==> $a = ++1 = 2result (where $a = 2) --> 2 + (2++) = 4

whereas otherwise:

$a = 1;++$a + $a++operand 2 --> $a++ ==> $a = 1// new operation on the left side// so the value gets incremented ==> $a = 2result (where $a = 2) --> (++2) + 2 = 5

I'm not sure about this, though.