HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Break & Continue

Sometimes you need to stop a loop early or skip certain parts of its code based on a specific condition. PHP provides two powerful keywords for this purpose: break and continue.


1. The break Keyword

The break statement is used to jump out of a loop entirely. Once a break is encountered, PHP stops the loop and continues with the first line of code after the loop block.

<?php
    for ($x = 0; $x < 10; $x++) {
        if ($x == 4) {
            break; // Exits the loop completely when $x is 4
        }
        echo "The number is: $x <br>";
    }
?>

2. The continue Keyword

The continue statement breaks one iteration (in the loop). If a specified condition occurs, it skips the rest of the code in that iteration and jumps to the next one.

<?php
    for ($x = 0; $x < 10; $x++) {
        if ($x == 4) {
            continue; // Skips 4 and goes straight to 5
        }
        echo "The number is: $x <br>";
    }
?>
Context: Both break and continue work in all types of PHP loops: for, while, do while, and foreach.
Pro Tip: Use break when searching through data (e.g., stop looping once the specific user is found) to save processing power.

Example: break in while loop

Breaking a loop helps prevent infinite execution or unnecessary processing.

<?php
    $x = 0;

    while($x < 100) {
        if ($x == 10) {
            break;
        }
        echo "Number: $x <br>";
        $x++;
    }
?>

Key Points to Remember

  • The break statement exits the loop immediately and entirely.
  • The continue statement skips only the current iteration.
  • Both keywords are usually triggered by an if condition inside the loop.
  • Using break can improve performance by stopping unnecessary work.
  • They are essential for handling exceptions or specific data patterns within lists.