2
$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.

Iamwhoiam
  • 159
  • 3
  • 12

3 Answers3

1

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

  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

MohitC
  • 4,541
  • 2
  • 34
  • 55
1

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.

Community
  • 1
  • 1
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
0

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

Shiji.J
  • 1,561
  • 2
  • 17
  • 31