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

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.