$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.
$b=$a+++$a++
– Dessertspoon+
guaranteed? If not, this is simply undefined behaviour. – Sternson$b = $a++ +$a;
is3
while$b = $a+ ++$a;
is4
!! Astonishing – Hecto$a++ + $a
(anything with the post-increment operator) depends on the undefined order of operations, while$a + ++$a
(anything with the pre-increment operator) should be guaranteed to always have the same result. – Sternson