Loading...
Loading...

PHP Continue Statement

The continue statement in PHP is used to skip the current iteration of a loop and continue with the next iteration. This can be particularly useful for filtering out specific conditions within loops.

1. Using continue in Loops

The continue statement can be used in for, while, and do-while loops. When encountered, it skips the remaining code in the current iteration and jumps to the next iteration of the loop.


// Example with a for loop
for ($i = 0; $i < 10; $i++) {
    if ($i % 2 == 0) {
        continue; // Skip even numbers
    }
    echo $i . " "; // Output odd numbers
}
// Output: 1 3 5 7 9

2. Using continue in a while Loop

The continue statement can also be applied within a while loop. This allows you to control which iterations should be processed.


// Example with a while loop
$i = 0;
while ($i < 10) {
    $i++;
    if ($i % 2 == 0) {
        continue; // Skip even numbers
    }
    echo $i . " "; // Output odd numbers
}
// Output: 1 3 5 7 9

3. Using continue with a Numeric Argument

You can also use the continue statement with a numeric argument in nested loops. This allows you to skip to the next iteration of a specific level of the loop.


// Example with nested loops
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($j == 2) {
            continue 2; // Skips to the next iteration of the outer loop
        }
        echo "i = $i, j = $j\n";
    }
}
// Output: i = 1, j = 1
//         i = 2, j = 1
//         i = 3, j = 1

Conclusion

The continue statement is a valuable tool in PHP for controlling the flow of loops. It enables you to efficiently skip iterations based on specific conditions, which can help optimize code execution.

0 Interaction
1.8K Views
Views
49 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home