Please, take a look at the following expression:
$x = 20;
echo $x+++$x++; // 41
Why is the answer 41
instead of 43
?
Please, take a look at the following expression:
$x = 20;
echo $x+++$x++; // 41
Why is the answer 41
instead of 43
?
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):
It is worth mentioning, though, that in this case the same results is obtained even if the expression is evaluated from the left.
$x+++$x++;
is
$x
(20)$x
(now $x
is 21)$x
(21)20 + 21 = 41
$x
(now $x
is 22)Another question to read - What's the difference between ++$i and $i++ in PHP?
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.