$x = 5; echo "$x"; echo "<br>"; echo $x+++$x++; echo "<br>"; echo $x;
Wouldn't the output of the code above be "5,12,5"? PHP outputs "5,11,7"?
Why? I am confuse.
$x = 5; echo "$x"; echo "<br>"; echo $x+++$x++; echo "<br>"; echo $x;
Wouldn't the output of the code above be "5,12,5"? PHP outputs "5,11,7"?
Why? I am confuse.
The first reference to $x is when its value is still 5 (i.e., before it is incremented) and the second reference to $x is then when its value is 6 (i.e., before it is again incremented), so the operation is 5 + 6 which yields 11. After this operation, the value of $x is 7 since it has been incremented twice.
So it's basically
Supply 5 as one of the operands to an addition operation.
Increment x after supplying it to addition operation (post increment), which makes it 6.
Supply this previous incremented x as second operand to the addition operation, which is 6. So it makes it 5+6, yields 11
Lastly increment x after addition operation making it 7
See notes in comments
$x = 5;
echo $x . PHP_EOL;
// now x=5
echo ++$x + $x . PHP_EOL;
// left side of the operation makes x=6 then the right side adds x to it, meaning 6+6
echo ++$x . PHP_EOL;
// now x=7
Also check this What's the difference between ++$i and $i++ in PHP?
to get some idea about pre vs. post incrementation.
$x ++ means the current value of x is 5, and immediately after that, x will be 6.
for the second x, x = 6, then immediately after that, x = 7.