PHP Mastery Tutorial 0/120 lessons ~6 min read Lesson 12

    Control Statements (Part 1)

    Learn PHP break and continue — stop loops early, skip iterations, nested break 2/continue 2, switch fall-through, and real-world patterns for login, search, and CSV import.

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    PHP Control Statements (Part 1)

    break and continue

    Introduction

    As your PHP applications become more advanced, you'll often need to control how your code flows. Sometimes you want to stop a loop immediately. Other times, you want to skip the current iteration and move to the next one.

    This is where Control Statements come into play.

    Control statements allow you to change the normal execution flow of your program. Instead of executing every line sequentially, you can decide when to stop, skip, or return from a block of code.

    Every professional PHP developer uses these statements daily—whether processing thousands of database records, validating user input, importing CSV files, or building REST APIs.

    In this lesson, we'll first learn the two most commonly used control statements:

    • break
    • continue

    These two keywords may look simple, but they are incredibly powerful when used correctly.

    What are Control Statements?

    Control statements are special language constructs that modify the normal flow of program execution.

    Normally, PHP executes code from top to bottom.

    php
    echo "First";
    echo "Second";
    echo "Third";

    Output: FirstSecondThird

    However, control statements allow PHP to:

    • Stop a loop
    • Skip an iteration
    • Exit a function
    • Stop the entire script
    • Jump to another part of the program (rarely used)

    Think of them as traffic signals for your code.

    • Green → Continue executing
    • Yellow → Skip this step
    • Red → Stop execution

    Why are Control Statements Important?

    Imagine processing 10,000 customer records.

    You discover an invalid record. Should your application continue? Should it stop immediately? Should it ignore only that record?

    Control statements give you complete control over these decisions.

    Without them, your code becomes complicated, slower, and difficult to maintain.

    The break Statement

    The break statement immediately terminates the nearest loop or switch statement.

    Once PHP encounters break, execution continues with the first statement after the loop.

    Syntax:

    php
    break;

    Example 1: Stop a Loop

    php
    <?php
    for ($i = 1; $i <= 10; $i++) {
    if ($i == 6) {
    break;
    }
    echo $i . "<br>";
    }
    1
    2
    3
    4
    5

    The loop stops as soon as $i becomes 6. Everything after that is ignored.

    How break Works

    Imagine the loop running like this:

    • Iteration 1 — ✔ Continue
    • Iteration 2 — ✔ Continue
    • Iteration 3 — ✔ Continue
    • Iteration 4 — ✔ Continue
    • Iteration 5 — ✔ Continue
    • Iteration 6 — ❌ break — Loop ends immediately.

    Real-World Example: Login Attempts

    Suppose your application allows only three login attempts.

    php
    <?php
    $attempts = [false, false, true];
    foreach ($attempts as $attempt) {
    if ($attempt) {
    echo "Login Successful";
    break;
    }
    echo "Invalid Login<br>";
    }
    Invalid Login
    Invalid Login
    Login Successful

    Once the user logs in successfully, there is no reason to continue checking. break saves unnecessary work.

    Imagine searching products.

    php
    <?php
    $products = [
    "Laptop",
    "Mouse",
    "Keyboard",
    "Monitor"
    ];
    foreach ($products as $product) {
    if ($product == "Keyboard") {
    echo "Product Found";
    break;
    }
    }

    The search stops immediately after finding the required product. Searching the remaining products would only waste processing time.

    Using break Inside a switch

    break is most commonly used with switch.

    php
    <?php
    $day = 3;
    switch ($day) {
    case 1:
    echo "Monday";
    break;
    case 2:
    echo "Tuesday";
    break;
    case 3:
    echo "Wednesday";
    break;
    default:
    echo "Invalid";
    }

    Without break, PHP would continue executing the following cases. This is called fall-through, and it's usually not what you want.

    Nested Loops and break

    Sometimes loops exist inside other loops.

    php
    <?php
    for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 5; $j++) {
    if ($j == 3) {
    break;
    }
    echo "$i - $j<br>";
    }
    }
    1 - 1
    1 - 2
    2 - 1
    2 - 2
    3 - 1
    3 - 2

    Only the inner loop stops. The outer loop continues normally.

    break 2

    PHP allows you to break out of multiple nested loops.

    php
    <?php
    for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= 5; $j++) {
    if ($j == 3) {
    break 2;
    }
    echo "$i-$j<br>";
    }
    }
    1-1
    1-2

    break 2 exits both the inner and outer loops immediately. This is useful when you find the result you're looking for and don't need to continue processing.

    When Should You Use break?

    Use break when:

    • You find the required record.
    • A validation fails and processing should stop.
    • An unrecoverable error occurs inside a loop.
    • You no longer need to iterate through remaining items.

    The continue Statement

    Unlike break, continue does not stop the loop.

    Instead, it skips the remaining code in the current iteration and moves to the next iteration.

    Syntax:

    php
    continue;

    Example 1: Skip Even Numbers

    php
    <?php
    for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 == 0) {
    continue;
    }
    echo $i . "<br>";
    }
    1
    3
    5
    7
    9

    Every even number is skipped. The loop itself continues.

    Understanding continue

    Imagine the loop running like this:

    • 1 ✔ Print
    • 2 ❌ Skip
    • 3 ✔ Print
    • 4 ❌ Skip
    • 5 ✔ Print

    The loop never stops. It simply ignores selected iterations.

    Real-World Example: Ignore Inactive Users

    php
    <?php
    $users = [
    ["name"=>"Rahul","active"=>true],
    ["name"=>"Priya","active"=>false],
    ["name"=>"John","active"=>true]
    ];
    foreach ($users as $user) {
    if (!$user['active']) {
    continue;
    }
    echo $user['name']."<br>";
    }
    Rahul
    John

    Inactive users are skipped without affecting the rest of the processing.

    Real-World Example: CSV Import

    Imagine importing thousands of records.

    php
    <?php
    foreach ($rows as $row) {
    if (empty($row['email'])) {
    continue;
    }
    // Save to database
    }

    Instead of stopping the entire import because of one invalid row, the script skips only the bad record and continues processing the rest. This is a common pattern in production systems.

    continue in Nested Loops

    php
    <?php
    for ($i = 1; $i <= 2; $i++) {
    for ($j = 1; $j <= 5; $j++) {
    if ($j == 3) {
    continue;
    }
    echo "$i-$j<br>";
    }
    }
    1-1
    1-2
    1-4
    1-5
    2-1
    2-2
    2-4
    2-5

    Only the current iteration of the inner loop is skipped.

    continue 2

    Like break, continue can also affect multiple loop levels.

    php
    <?php
    for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 5; $j++) {
    if ($j == 3) {
    continue 2;
    }
    echo "$i-$j<br>";
    }
    }

    When $j becomes 3, PHP skips the remainder of the inner loop and immediately starts the next iteration of the outer loop.

    Use this feature carefully—it can make code harder to follow if overused.

    break vs continue

    StatementWhat it DoesLoop Continues?
    breakStops the loop immediately❌ No
    continueSkips the current iteration✅ Yes

    Remember: break = Exit the loop. continue = Skip this iteration and keep going.

    Best Practices

    • Use break when further processing is unnecessary.
    • Use continue to ignore invalid or irrelevant data while continuing the loop.
    • Keep loop conditions simple and readable.
    • Add comments if break 2 or continue 2 are used, as they can be confusing for other developers.
    • Prefer meaningful variable names so the loop logic is easy to understand.

    Common Mistakes

    Using break Instead of continue

    If you only want to ignore one record, use continue. Using break will stop processing all remaining records.

    Forgetting break in switch

    Missing break statements can cause unexpected fall-through, executing multiple cases unintentionally.

    Overusing Nested Loop Controls

    Frequent use of break 2 or continue 2 may indicate that your logic can be refactored into smaller functions.

    Writing Complex Conditions Inside Loops

    If your loop contains many nested if statements, consider moving the logic into helper functions for better readability.

    Summary

    Control statements help you write efficient, readable, and maintainable PHP code.

    Use break to stop a loop when you have completed your task. Use continue to skip unwanted data while allowing the loop to continue processing.

    Mastering these two statements will help you build faster applications, process large datasets efficiently, and write cleaner code.

    What's Next?

    In Control Statements (Part 2), we'll explore return, exit(), die(), and goto, along with real-world project scenarios.

    Continue at /learn/php/control-statements-part-2.

    Ready to mark this lesson complete?Track your journey across the entire course.