If I try this:
$a = 0;
echo $a + ++$a, PHP_EOL;
echo $a;
I get this output:
2
1
Demo: http://codepad.org/ncVuJtJu
Why is that?
I expect to get this as an output:
1
1
My understanding:
$a = 0; // a === 0
echo $a + ++$a, PHP_EOL; // (0) + (0+1) === 1
echo $a; // a === 1
But why isn’t that the output?
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:
Notes:
Operator precedence does not determine the order of evaluation. Operator precedence only determines that the expression
$l + ++$lis 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.Operator associativity also does not determine order of evaluation. That the
+operator has left associativity only determines that$a+$b+$cis 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?”