Unintuitive expression evaluation with incrementation
Solution 1:
$a=1; $b=$a+$a++; var_dump($b); // int(3)
You assumed that the expression above is evaluated from left to right as follows (temporary variables $u
and $v
are introduced in the explanation for clarity):
$a = 1;
$u = $a; // ($a) the LHS operand of `+`
$v = $a; // \ ($a++) the RHS operand of `+`
$a ++; // /
$b = $u + $v; // 2 (1+1)
But there is no guarantee that the subexpressions are evaluated in a specified order. The documentation page of the PHP operators states (the emphasis is mine):
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
Only by chance the values computed by PHP for the other expressions match the values you assumed. Their values might be different when the code is executed using a different version of the PHP interpreter.
Solution 2:
PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided [..]
http://php.net/manual/en/language.operators.precedence.php
The reason you get differing results is that sometimes the right and sometimes the left operand are evaluated first. PHP makes no guarantees about the order of operations, so there is no correct answer and this falls squarely into the category of undefined behaviour.
Solution 3:
According to PHP manual
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3
$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>
The weird thing is that I'd have expected the other lines like $b=$a+$a+$a++;
follow the same pattern, but it seems not.