PHP Continue Statement: Skipping Iterations & Multi-Level Flow Control

While the break statement terminates a loop completely, the continue statement offers a surgical alternative: it skips the remainder of the current iteration only and jumps straight to the loop's next iteration. This makes continue the ideal tool for filtering out unwanted records, ignoring invalid values, and writing clean, readable loops.

Basic Usage of continue

In this example, we iterate through numbers 1 to 10, but use continue to skip all even numbers so only odd numbers are printed:

<?php
    for ($i = 1; $i <= 10; $i++) {
        // If number is even, skip this iteration
        if ($i % 2 === 0) {
            continue; // Jumps directly to $i++ for the next iteration
        }
        echo "Odd Number: " . $i . "<br>";
    }
?>

Data Filtering Example: Skipping Inactive Users

In web applications, continue acts as an elegant guard clause to ignore records that do not meet processing criteria:

<?php
    $students = [
        ["name" => "Deepak", "feesPaid" => true,  "marks" => 85],
        ["name" => "Ritu",   "feesPaid" => false, "marks" => 92], // Fee pending
        ["name" => "Suresh", "feesPaid" => true,  "marks" => 78],
        ["name" => "Kavita", "feesPaid" => false, "marks" => 65]  // Fee pending
    ];

    echo "<h4>Issuing Hall Tickets to Eligible Students:</h4><ul>";
    foreach ($students as $s) {
        if (!$s['feesPaid']) {
            // Skip students who haven't cleared fees
            continue;
        }
        echo "<li>Hall Ticket Issued to: " . $s['name'] . " (Score: " . $s['marks'] . ")</li>";
    }
    echo "</ul>";
?>

Multi-Level Continue (continue n)

Just like break, you can pass a numeric argument to continue to skip iterations of outer loops:

<?php
    for ($batch = 1; $batch <= 3; $batch++) {
        for ($student = 1; $student <= 4; $student++) {
            if ($batch === 2 && $student === 2) {
                echo "Skipping remainder of Batch 2!<br>";
                continue 2; // Skips to the next iteration of the OUTER loop ($batch++)
            }
            echo "Batch $batch, Student $student<br>";
        }
    }
?>

BCA / CS University Exam Corner

High-Frequency Exam Question:

Q: What danger exists when using continue inside a while loop?
A: If the increment statement ($i++) is placed after the continue line, skipping the iteration will skip the counter increment, trapping the while loop in an infinite loop! In while loops, always increment before calling continue.

Interactive Student Practice Session

Exercise 20.1: Write a loop that processes numbers from 1 to 20, skipping all multiples of 3 using continue.

Exercise 20.2: Write a script that iterates over an array of email addresses, skipping any item that does not contain the "@" symbol.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!