简体   繁体   中英

PHP equation output confusion

$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 (ie, before it is incremented) and the second reference to $x is then when its value is 6 (ie, 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

  1. Supply 5 as one of the operands to an addition operation.

  2. Increment x after supplying it to addition operation (post increment), which makes it 6.

  3. Supply this previous incremented x as second operand to the addition operation, which is 6. So it makes it 5+6, yields 11

  4. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM