Why $x=5; $x+++$x++; equals with 11 in PHP?
It took me a few reads, but $x=5; $x++ + $x++;
works like this:
In the case of a $x++, it first 'gets used', then increased:
- Set $x to 5
- Place $x onto stack (which is 5)
- Increment(
++
) ($x is now 6, stack=[5]) - Add $x onto stack (stack=[5,6], so 5+6 -> $x=11)
- Adding is done, that outcome is 11
- Increment $x(
++
) (which is isn't used further, but $x is now 7)
Actually, in this specific example, if you would echo $x;
it would output 7. You never reassign the value back to $x, so $x=7 (you incremented it twice);
$x = 5;
$a = $x++ + $x++;
the expression line will be executed like this:
1st occurrence of $x++
in the statement will increment $x
value by 1 so it will become 6 and
in 2nd occurrence, $x
will be having value 6;
So $a = 5 + 6;
So final result $a
will be 11.
++ has higher precedence than + operator
(x++) will return the value of x first then increment it by 1
$x = 2
$x++ // return 2, then increment it to 3
x+++x++ is evaluated like the following
1. Get x value first which is 5
2. Then it will be incremented to 6
3. But first x value will be 5 because (x++) statement will return 5 first then increment the value
4. Then + operator is encountered
5. Next x will have 6 as value not 7 for the same reason (x++) will return the x value first and then increment it
6. So 5+6 is 11
7..At the end, x value will be 7
Same goes for ($x++)+($x++)
grouping operator ()
has left to right
associatevity. First ($x++)
executes first.
$x = 5
($x++) returns 5 and then increment $x by 1. Same as before.
then last ($x++) executes. It returns 6 and then increment $x to 7
so same 5+6 // 11
is returned back