Continue Statement in PHP

In PHP, the continue statement is used within loops to skip the remaining code inside the loop's current iteration and move to the next iteration. It's typically used when you want to skip certain iterations based on a specific condition, without terminating the loop entirely.

Here's how the continue statement works within different loop contexts:

Example
for ($i = 0; $i < 5; $i++) {
    if ($i == 2) {
        continue; // Skip iteration when $i is equal to 2
    }
    echo $i . "<br>";
}

In this example, the loop iterates from 0 to 4. When $i is equal to 2, the continue statement skips the remaining code inside the loop's current iteration, and the loop proceeds directly to the next iteration.

While Loop
$i = 0;
while ($i < 5) {
    $i++;
    if ($i == 2) {
        continue; // Skip iteration when $i is equal to 2
    }
    echo $i . "<br>";
}

This while loop behaves similarly to the for loop example. When $i is equal to 2, the continue statement skips the remaining code inside the loop's current iteration, and the loop proceeds to the next iteration.

Do While Loop
$i = 0;
do {
    $i++;
    if ($i == 2) {
        continue; // Skip iteration when $i is equal to 2
    }
    echo $i . "<br>";
} while ($i < 5);

In this do-while loop example, the behavior is the same as the previous examples. The continue statement skips the remaining code inside the loop's current iteration when $i is equal to 2.

The continue statement can be useful for skipping certain iterations of a loop based on specific conditions, while allowing the loop to continue executing.

Next Article ❯