In the PHP manual, operator precedence section, there is this example:
// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5
I understand the behavior is undefined because of the following reason:
Since x + y = y + x
the interpreter is free to evaluate x
and y
for addition in any order in order to optimize speed and/or memory. I concluded this after looking at the C code example in this article.
My question is that the output of the above mentioned PHP code should be 4
no matter which way the expression and sub-expressions are evaluated:
- op1 = ++$a => $a = 2, op1 = 2; op2 = $a++ => op2 = 2, $a = 3; 2 + 2 = 4
- op1 = $a++ => op1 = 1, $a = 2; op2 = ++$a => op2 = 3, $a = 3; 1 + 3 = 4
Where does the 5 come from? Or should I learn more about how the operators work?
Edit:
I have been staring at Incrementing/Decrementing Operators section but still could not figure out why 5.
++$a: Pre-increment -- Increments $a by one, then returns $a.
$a++: Post-increment -- Returns $a, then increments $a by one.