Today I saw an interesting problem. At first glance I wasn’t sure what I was looking at. It took me a moment to parse it.

Here is my own version of the problem:

$x = 3;
echo $x;
echo "<br />";
echo $x+++$x++;
echo "<br />";
echo $x;
echo "<br />";
echo $x---$x--;
echo "<br />";
echo $x;

The question is “What will the output be?”

First, you have to realize that the +++ and --- are not one entity.

This is what it actually is: echo $x++ + $x++;

Now it’s easy to see what is going on. However, this is a test of your knowledge of post-fix vs pre-fix increment and decrement operators.

Post-fix means that the increment happens “after”. But after what? In this case, it happens after the value in the variable is “presented” to be added.

Our initial value was 3. So let’s break it down as follows:

echo 3 + $x++;

But remember that the post-fix increment happens right after the 3 is placed on the left side of the addition.

So that makes it:

echo 3 + 4;

And then the value of x is incremented again, due to the second post-fix operator. If you are tracking the value of x, you’ll know that it’s now 5 at this point.

Here is another way to think of it: Present x for the left side, then increment it. Jump to the other side, and now x is 4. Then increment it again *after* the addition.

So, the output so far would be:

3 // Original value

7 // Result of the addition

5 // Due to the last post-fix increment done after the addition

I’ll leave the remainder of the problem for the reader to solve.

Post-Fix Increment Problem with Solution