Continue vs. Break (in while loops)

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

Comments are closed.