Jump to content

for loop followed by a while loop


wright67uk

Recommended Posts

The output for the below code is;

 

the for loop number is 0

the for loop number is 1

the for loop number is 2

the for loop number is 3

the for loop number is 4

the for loop number is 5

the while loop number 7

the while loop number 8

the while loop number 9

 

$i = 0;
for ($i=0; $i<6; $i++)
{echo "the for loop number is $i <br/>";}

while ($i<9)
{$i++ ;
echo "the while loop  number $i <br/>";}

 

If at the end of my for loop $i = 5, and then in my while loop 1 is added to $i  ($i++) then why doesnt my while loop

output begin with;    the while loop number 6  ?

Link to comment
https://forums.phpfreaks.com/topic/259452-for-loop-followed-by-a-while-loop/
Share on other sites

Att he end of the for loop $i actually has the value of 6 - not 5. The for() loop condition is to continue as long as $i<6. So when it equals five the for loop will run, then $i is incremented to 6 and the for loop will exit. Therefore, when the while loop starts it first increments $i (to 7). So the first output from the while loop would be

 

"the while loop  number 7"

 

If you want to start the while loop output at 6, then increment $i after you do the output.

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.