[Solved] What would be the output of $a + $a++ + $a++ with $a = 1


This might be better explained with a shorter example:

$a = 1;
echo $a + $a++;

This might look like it should equal 2. The post-increment operator ($a++) returns the “before” value of the variable, so it should return 1. And 1+1 equals 2.

However, what’s actually happening is that $a++ is getting evaluated first. So the post-increment operator runs, and returns 1, but by the time the rest of the evaluation happens, $a has been incremented to 2. So this ends up evaluating 2 + 1;

Your example comes down to:

  • Run the first $a++, returning 1. $a is now 2;
  • Evaluate the sum 2 + 1 (the new $a value and the return from the post-incr operator), returning 3
  • Run the second $a++ (the end of the line), returning 2 (the value of $a before the increment). $a is now 3;
  • Evaluate the second sum, 3 + 2, returning 5

In short, please don’t write lines of code like this. They’re an interesting experiment if you want to know how PHP works internally, but they aren’t remotely intuitive.

Edit to add: @Narf’s comment below is important too. This is undefined behaviour, and shouldn’t be relied upon. In fact, the answer did indeed come out differently in PHP < 5.1. See https://3v4l.org/sqCkW

1

solved What would be the output of $a + $a++ + $a++ with $a = 1