1

Please, take a look at the following expression:

$x = 20;

echo $x+++$x++; // 41

Why is the answer 41 instead of 43?

Beso Kakulia
  • 139
  • 1
  • 6

3 Answers3

5

Altough I can't find any mention in the PHP docs, I guess PHP evaluates from right, and ++ acts like the same operator in C/C++ (see inc/dec PHP operator docs)

So, the expression:

$x+++$x++

in fact does (evaluated from the right):

  1. get the value of x → 20
  2. increment the value of x → 21
  3. get the value of x → 21
  4. increment the value of x → 22
  5. sum the values got from 1 and 3 → 41

It is worth mentioning, though, that in this case the same results is obtained even if the expression is evaluated from the left.

watery
  • 5,026
  • 9
  • 52
  • 92
1

$x+++$x++; is

  1. Start getting sum of values
  2. First value is $x (20)
  3. Increment $x (now $x is 21)
  4. Second value is $x (21)
  5. Get sum of first and second values - 20 + 21 = 41
  6. Increment $x (now $x is 22)

Another question to read - What's the difference between ++$i and $i++ in PHP?

Community
  • 1
  • 1
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

The expression

$x+++$x++

is evaluated as

($x++) + ($x++)

The $x++ returns the value of the $x and then increments it by 1. So, this:

$x = 20;
$y = $x++;

You end up with $y == 20 and $x == 21. Now, applying this to your expression:

$x = 20;
($x++) + ($x++);

We get first $x++ returned as 20 while incrementing $x to 21; and the second $x++ returned as 21 while incrementing $x to 22. So:

20 + 21

which evaluates to 41, but note that $x is now set to 22.

Unix One
  • 1,151
  • 7
  • 14