scriptygoddess

25 Oct, 2004

Continue vs. Break (in while loops)

Posted by: Jennifer In: Lessons learned

(note to self type post)
Using "continue" in the middle of a while loop will skip the current iteration and go back to the beginning of the loop (checking the while value again).

Using "break" in the middle of a while loop will break the loop entirely. (no more looping)

So this code

<?php
$i = 0;
while ($i < 5) {
$i++;
if ($i%2) {
echo "value = " .$i . " – inside if<br>";
continue;
}
echo "value = " .$i . " – outside if<br>";
}
?>

Will produce this:
value = 1 – inside if
value = 2 – outside if
value = 3 – inside if
value = 4 – outside if
value = 5 – inside if

Where as this

<?php
$i = 0;
while ($i < 5) {
$i++;
if ($i%2) {
echo "value = " .$i . " – inside if<br>";
break;
}
echo "value = " .$i . " – outside if<br>";
}
?>

Will produce this:
value = 1 – inside if

See more about while loops here.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

No Responses to "Continue vs. Break (in while loops)"

Comments are closed.

Featured Sponsors

About


Advertisements