What's the Difference Between "$i++" and "++$i" in PHP?

In PHP, both i++ and ++i are increment operators used for adding 1 to a variable "i". However, they behave differently in terms of when the increment occurs:

  • i++ — this is called the postfix increment operator, which first returns the current value of i, and then increments i;
  • ++i — this is called the prefix increment operator, which increments i first, and then returns the new value.

To see the differences, you can compare the following examples for both, the postfix (i++) and prefix (++i) increment operators:

$i = 0;
echo $i++; // 0
echo $i; // 1
$i = 0;
echo ++$i; // 1
echo $i; // 1

As you can see in the examples above, $i++ returns the current value of i first and then increments it, while ++$i does the opposite.

Using either one in the increment part of a for loop, however, will yield the same result:

for ($i = 0; $i < 5; $i++) {
    echo $i; // 0 1 2 3 4
}
for ($i = 0; $i < 5; ++$i) {
    echo $i; // 0 1 2 3 4
}

This is because the order of execution of a for loop is always the same, where the increment part of a for loop is executed last, and the loop body is always executed before it. This is why the result is the same regardless of whether you use the prefix or postfix increment operator in the increment part of a for loop.

However, this is not the same as using the prefix and postfix operators in the body of a for loop:

for ($i = 0; $i < 5;) {
    echo $i++; // 0 1 2 3 4
}
for ($i = 0; $i < 5;) {
    echo ++$i; // 1 2 3 4 5
}

Here, in the loop's body, depending on which operator you use, the return values are different (as expected). This is the same as when you increment the counter inside the body of a while loop for example:

$i = 0;
while ($i < 5) {
    echo $i++; // outputs 0, 1, 2, 3, 4
}
$i = 0;
while ($i < 5) {
    echo ++$i; // outputs 1, 2, 3, 4, 5
}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.