continue skips the rest of the current round and jumps to the next one. The loop itself keeps running.
<?php
for ($i = 1; $i <= 6; $i++) {
if ($i % 2 === 0) {
continue; // skip even numbers
}
echo $i . " ";
}
1 3 5
For the even numbers, PHP skipped the echo and went straight to the next $i.
break vs continue
| What happens | |
|---|---|
break | The whole loop ends |
continue | Only this round ends. The loop goes on |
Skip invalid items
A common use is to ignore items you cannot process.
<?php
$emails = ["a@example.com", "", "not-an-email", "b@example.com"];
foreach ($emails as $email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
continue;
}
echo "Sending to $email\n";
}
Sending to a@example.com
Sending to b@example.com
Notice the style: the invalid case is dealt with first and the main work stays at the same indentation level. This “guard” style avoids a deep if inside the loop.
continue in while loops: be careful
In a while loop, continue jumps back to the condition. Make sure the counter is updated before it.
<?php
$i = 0;
while ($i < 5) {
$i++; // update first
if ($i === 3) {
continue;
}
echo $i . " ";
}
1 2 4 5
If $i++ were at the bottom, the continue would skip it, and the loop would never end when $i equals 3.
continue 2 in nested loops
continue 2 skips to the next round of the outer loop.
<?php
foreach (["Ann", "Ben"] as $name) {
foreach ([1, 2, 3] as $number) {
if ($number === 2) {
continue 2;
}
echo "$name-$number ";
}
}
Ann-1 Ben-1
The update that never runs
while loop, a continue that comes before the counter update causes an infinite loop. Update first, or use a for loop, where the step always runs.