ngatran Posted April 15, 2013 Share Posted April 15, 2013 I'm learning PHP for loop and this is a problem I couldn't quite understand. Could anyone please help me to explain the difference in the results of these two codes? <?php for ($i=0; $i<10;$i++) // the result is 02468 {echo $i++;} ?> <?php for ($i=0; $i<10;$i++) // the result is 13579 {echo ++$i;} ?> I know the difference here lies in $i++ (post-increment) and ++$i (pre-increment). However, I couldn't figure out the process that PHP works to give out the results. Can anyone help me with these? Thank you very much. Quote Link to comment Share on other sites More sharing options...
Jessica Posted April 15, 2013 Share Posted April 15, 2013 Well it's kind of obvious from your results. But you could also read the manual. http://php.net/manual/en/language.operators.increment.php Quote Link to comment Share on other sites More sharing options...
DavidAM Posted April 15, 2013 Share Posted April 15, 2013 In the first case, you echo the value of $i before it is incremented, so you echo 0, then 2, then 4, then 6, then 8. In the second case you echo the value of $i after it is incremented, so you echo 1, then 3, then 5, then 7, then 9. In both cases, since you are incrementing the control variable ($i) inside the loop (in the echo statement), the loop skips numbers (it is also being incremented in the for statement -- at the end of the loop body). Since you did not echo any punctuation, it appears to echo a single large number. The first loop is functionally equivalent to: for ($i = 0; $i < 10; $i++) { /* Loop Body */ // First pass $i == 0 here // Second pass $i == 2 here echo $i; $i++; // First Pass: $i == 1 // Second Pass: $i == 3 } /* End of the loop body -- increment $i First Pass: $i == 2 Second Pass: $i == 4 if ($i < 10) Go back to first line in loop body */ This is not unique to PHP. Any language that supports for loops and pre-/post- increments will produce the same result. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.