How are they different? Here's what I'm thinking, but I'm not sure....
If you use pre-incrementation, for example in a for loop with ++j, then you are basically saying: "Make a copy of the value of j for use in the loop, then increment j, then go through the statements in the loop with the copy of j." If you are using post-incrementation in the same loop j++, then you are basically saying: "Make a copy of the value of j for use in the loop, then go through the statements in the loop with the copy of j, then increment j."
The reason I'm unsure is because I've created a for loop that multiplies the value of j by 10 and then outputs the result for j=1 through j=12, using both post- and pre-incrementation. The human readable output is exactly the same with post- and pre-incrementation. I'm thinking, 'How are the outputs exactly the same if there isn't some kind of copy operation involved?'
So, I'm guessing the difference between pre- and post-incrementation truly becomes important, in php, when I use references (which act as pointers in php) rather than names for return values? This would be because copies of references aren't made, so pre-incrementation would be: "Increment j, then go through the statements in the loop with the changed value of j, then increment j again...," whereas post-incremetation would look like: "Use the value of j for the statements in the loop, then change the value of j, then go through the loop with the new value of j..."
Pre- or post-incrementing do not magically delay things until later. It's simply inline shorthand.
Now let's look at a loop.
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.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:
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.
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.