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
https://forums.phpfreaks.com/topic/276953-confusion-in-php-for-loop/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.