Jump to content

Confusion in PHP for loop.


ngatran

Recommended Posts

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.

Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.