This is propably a farcical “problem” but I just don’t see the reason for this behaviour.
Facts:
$i++;
returns the current value and then increments $i by one.
++$i;
increments $i by one and then returns $i.
Situations:
for($i = 0; $i < 10; ++$i){
echo $i."\n";
}
gives
0
1
2
3
4
5
6
7
8
9
2nd:
for($i = 0; $i < 10; $i++){
echo $i."\n";
}
gives also
0
1
2
3
4
5
6
7
8
9
If I’d take the documentation of the increment literally, I would explain the loops as follows:
- at the end of each iteration, $i is incremented by one and then
returned, so we’ve got at first a 0 because $i started as 0, then a 1 etc. - at the end of each iteration, $i is returned and THEN incremented,
which would, exactly, mean that there were two iterations where $i =
0.
It’s a fact that this is not true. Could somebody please explain, why?
$iis not being returned, it is being used (by you). Big difference.If you were to rewrite your
ifstatements to instead use awhileloop, you’d have these:Post-increment:
Pre-increment:
As you can see, there’s no difference between the two.
Here’s what the 3 statements you supply to the for loop are for:
at no point is the returned value of the 3rd statement being utilized in any way.
P.S. As mentioned, the third statement is run after every loop including the last one. This is evident by accessing the
$ivariable after the loop has completed:which would list all the numbers up to and including 10.
See it here in action: http://viper-7.com/Y6N2jU