wright67uk Posted March 21, 2012 Share Posted March 21, 2012 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 ? Quote Link to comment https://forums.phpfreaks.com/topic/259452-for-loop-followed-by-a-while-loop/ Share on other sites More sharing options...
Psycho Posted March 21, 2012 Share Posted March 21, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/259452-for-loop-followed-by-a-while-loop/#findComment-1330004 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.