Why is $a + ++$a == 2? Why is $a + ++$a == 2? php php

Why is $a + ++$a == 2?


All the answers explaining why you get 2 and not 1 are actually wrong. According to the PHP documentation, mixing + and ++ in this manner is undefined behavior, so you could get either 1 or 2. Switching to a different version of PHP may change the result you get, and it would be just as valid.

See example 1, which says:

// mixing ++ and + produces undefined behavior$a = 1;echo ++$a + $a++; // may print 4 or 5

Notes:

  1. Operator precedence does not determine the order of evaluation. Operator precedence only determines that the expression $l + ++$l is parsed as $l + (++$l), but doesn't determine if the left or right operand of the + operator is evaluated first. If the left operand is evaluated first, the result would be 0+1, and if the right operand is evaluated first, the result would be 1+1.

  2. Operator associativity also does not determine order of evaluation. That the + operator has left associativity only determines that $a+$b+$c is evaluated as ($a+$b)+$c. It does not determine in what order a single operator's operands are evaluated.

Also relevant: On this bug report regarding another expression with undefined results, a PHP developer says: "We make no guarantee about the order of evaluation [...], just as C doesn't. Can you point to any place on the documentation where it's stated that the first operand is evaluated first?"


A preincrement operator "++" takes place before the rest of the expression it's in evaluates. So it is actually:

echo $l + ++$l; // (1) + (0+1) === 2


a + ba = 1b = ++a:= 2

Why do you expect something else?

In PHP:

$a = 0;$c = $a + ++$a;

Operator precedence visualized:

$c = ($a) + (++$a);

Evaluation sequence visualized:

$a = 0; ($a = 0)$a = 1; (++$a)$c = $a + $a (1 + 1);

Or written out:

The moment the sum operation is performed, $a is already 1 because ++$a has been already evaluated. The ++ operator is evaluated before the + operator.


For the fun:

$a++ + ++$a

Results in 2, too. However if you compare it as an expression, it's not equal:

$a++ + ++$a == $a + ++$a

Where as

$a++ + ++$a == $a-- + --$a 

is "equal".


See Also: