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

The php manual states that:

$a = 1; echo ++$a + $a++; 

ambiguous in its grammar, but it seems extremely clear to me. ++ $ a and $ a ++ are evaluated first, from left to right, so ++ $ a increases and then returns 2, and $ a ++ returns 2, and then increases. The sum of 2 + 2 is 4, so it will be echo 4. However, the PHP manual says very clearly that it can print 4 or 5.

Does the php specification indicate that operations will be performed from left to right?

Even if this does not guarantee that the operations will be performed from left to right, in this case, will it not return 4 independently?

Edit: I re-read the page, and she stated that it is determined by each specific operator. + has the lowest priority and evaluates from left to right, so it seems that my previous assumption was correct. I still do not understand.

+8
php operator-precedence interpreter grammar
source share
2 answers

Please note that this is only my humble opinion.

I think the idea below this result is that none of the aperands takes precedence when there is one operator, and that in the operation the variable is saved as a link instead of replacing it with the result during all calculations to the last (plus in this example) . Therefore, when it comes from lr:

 $a = 1; ++$a + $a++ operand 1 --> ++$a ==> $a = ++1 = 2 result (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 = 2 result (where $a = 2) --> (++2) + 2 = 5 

I am not sure about that.

+3
source share

++$a let $a equal to 2 and return 2, $a++ increment $a , so $a now equal to 3, but returns 2.

In the same version of PHP, the result is always the same. But this may lead to a different result if the version of PHP changes. It depends on ++$a and $a++ , which is first evaluated. If $a++ is evaluated first, the result will be 5, otherwise the result will be 4.

+5
source share

All Articles