The PHP Continue Statement
Where break ends a loop completely, continue only gives up on the current pass. PHP ignores the rest of the loop body for this iteration and goes on to the next one.
All four loop types support it:
forwhiledo...whileforeach
PHP continue in For Loops
In a for loop, continue jumps past the remaining code in the body. The counter is still updated, and the loop goes on from there.
Continue in For Loop
Every number from 0 to 9 is printed except 4, because the echo is skipped when $x equals 4:
Output: PHP script
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
PHP continue in While Loop
A while loop treats continue the same way: the rest of the body is skipped for this pass and PHP goes back to checking the condition.
Continue in While Loop
Nothing is printed for the pass where $x equals 4, and the loop then goes on. Notice that $x is increased before continue: the keyword jumps straight back to the condition, so without that line $x would stay at 4 and the loop would never end.
Output: PHP script
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
$x++;
continue;
}
echo "The number is: $x <br>";
$x++;
}
?>
PHP continue in Do While Loop
In a do...while loop, continue sends PHP straight to the condition at the bottom, skipping any code left in the body.
Continue in Do While Loop
When $i is 3, the echo is skipped, so the output jumps from 2 to 4:
Output: PHP script
<?php
$i = 0;
do {
$i++;
if ($i == 3) continue;
echo $i;
} while ($i < 6);
?>
PHP continue in Foreach Loop
Use continue in a foreach loop to leave out certain elements: PHP ignores the rest of the body for that element and picks up the following one.
Continue in Foreach Loop
All the colors are printed apart from "blue":
Output: PHP script
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
if ($value == "blue") continue;
echo "$value<br>";
}
?>