Pre-incrementation vs. post-incrementation

Pre- or post-incrementing do not magically delay things until later. It’s simply inline shorthand.

enter image description here

// pre-increment
$var = 5;
print(++$var); // increments first, then passes value (now 6) to print()

// post-increment
$var = 5;
print($var++); // passes value (still 5) to print(), then increments

Now let’s look at a loop.

for ($i = 0; $i < 9; $i++) {
    print($i);
}

The last part of the loop declaration (the $i++) is simply the statement to execute after each time through the loop. It “passes” the value to nowhere, then increments it. $i isn’t used anywhere at that time. Later when the next statement is executed (print($i);), the value of $i has already increased.

// add 1, then do nothing with $i
for ($i = 0; $i < 9; ++$i) {}

// do nothing with $i, then add 1
for ($i = 0; $i < 9; $i++) {}

Whichever way you do it, $i will be the same within the loop.


If it helps, you can think of them as small routines that kind of do this:

// ++$i
{
    $i = $i + 1;
    return $i;
}

// $i++
{
    return $i;
    $i = $i + 1;
}

As I reread your question, I think the confusion is more with how the loop works than how increment operators work. Keeping in mind that the increment is a straightforward, all-at-once operation, here’s how third expression in the loop works.

// here's a basic loop
for ($i = 0; $i < 9; $i++) {
    // do loop stuff
    print($i);
}

// this is exactly what happens
for ($i = 0; $i < 9; ) {
    // do loop stuff
    print($i);

    $i++;
}

Just because that last line can be put in the loop declaration doesn’t give it any special powers. There are no references or anything used behind the scenes. The same $i variable is seen both inside and outside the loop. Every statement inside or outside the loop directly looks up the value of $i when necessary. That’s it. No funny business.

Leave a Comment