Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The php manual claims that:

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

is ambiguous under its grammar, but it seems extremely clear to me. ++$a and $a++ evaluate first, from left to right, so ++$a increments and then returns 2, and $a++ returns 2 and then increments. The sum of 2 + 2 is 4, so it would echo 4. However, The PHP Manual says very clearly that it may print 4 or 5.

Does the php spec not specify that operations will be performed from left to right?

Even if it doesn't enforce that operations will be performed from left to right, in this case, wouldn't it return 4 regardless?

Edit: I reread the page, and it stated that it is determined by each specific operator. + has lowest precedence, and evaluates from left to right, so it seems like my earlier assumption was correct. I still do not understand.

like image 313
nnythm Avatar asked Apr 05 '12 01:04

nnythm


2 Answers

++$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.

like image 53
xdazz Avatar answered Oct 19 '22 09:10

xdazz


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 = 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'm not sure about this, though.

like image 39
inhan Avatar answered Oct 19 '22 09:10

inhan