In PHP, the continue statement is used to skip the remaining code in the current loop iteration and move directly to the next iteration. It’s commonly used when you want to ignore certain conditions during looping.
<span class="fun">continue;</span>
You can also specify the number of loop levels to skip when using nested loops:
<span class="fun">continue 2; // skips the outer loop</span>
The continue statement is typically used in scenarios such as:
The following example demonstrates how to skip even numbers using continue:
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue;
}
echo $i . "\n";
}
?>
Output:
1
3
5
7
9
This example outputs "Fizz" for multiples of 5 and "Buzz" for multiples of 3, skipping the rest of the logic when those conditions are met:
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 5 == 0) {
echo " Fizz";
continue;
} elseif ($i % 3 == 0) {
echo " Buzz";
continue;
}
echo $i;
}
?>
Output:
<span class="fun">12 Fizz4 Buzz Fizz78 FizzBuzz</span>
The continue statement is a powerful tool for controlling loop execution in PHP. It helps write cleaner and more efficient code by skipping over logic that doesn’t need to run under certain conditions.