Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 147 ยท Control Flow

break, continue and Loop Control

Learn PHP break and continue - leaving loops early, skipping iterations, break 2 and continue 2 in nested loops and switch, why to avoid goto, and guard clauses.

Loops normally run until their condition says stop, or until foreach runs out of elements. Often you know earlier: you were searching for one item and just found it, or the current row is invalid and there's no point processing it. PHP gives you two statements to take control: break leaves a loop immediately, and continue skips the rest of the current iteration and moves on to the next one.

This lesson covers both, including the numeric levels (break 2, continue 2) for nested loops and switch, the classic continue bug in while loops, PHP's rarely used goto, and the technique that makes all of this cleaner: guard clauses and early returns, which keep your code flat instead of nested five levels deep. You should be comfortable with while, do-while and for Loops and foreach Loops first.

break: leave the loop now

break ends the innermost loop at once. PHP skips the rest of the body, doesn't check the condition again, and continues with the first statement after the loop. It's the natural tool for searches: once you've found what you were looking for, stop looking.

PHP Stopping a search with break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The loop stops after three orders instead of five. With five elements the saving is tiny, but with a million database rows or an expensive check per item, stopping early matters. Note the $firstFailed = null before the loop: if nothing matches, the loop finishes normally and the variable still has a sensible value.

Tip: For simple searches, PHP 8.4 added array_find(), which returns the first element for which a callback returns true (or null), and stops as soon as it finds one: array_find($orders, fn($o) => $o['status'] === 'failed'). See array_map, array_filter and array_reduce.

while (true) with break

Sometimes the natural place to decide whether to stop is in the middle of the loop body, not at the start or end. Write the loop as while (true) and break at that point:

PHP A command loop that quits on demand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The preset input has an add 100 after quit, and it never runs: the loop ended at quit. The second break handles the end of input, so the loop can't spin forever if the user never types quit. Every while (true) loop needs at least one reachable break (or return, or exit).

continue: skip to the next iteration

continue stops the current iteration and jumps straight to the next one. In a for loop that means the update expression ($i++) runs and the condition is checked; in foreach, the loop moves to the next element. It's ideal for skipping items that don't need processing:

PHP Skipping rows with continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each continue handles one reason to skip a line, and the "real work" at the bottom of the loop only sees valid rows. Compare that with wrapping the work in three nested if blocks: the flat version is much easier to read and to extend. The [$item, $qty] = explode(...) line uses destructuring, covered in Destructuring and Spread.

The continue trap in while loops

In a for loop, continue still runs the update expression. In a while loop, the update is just a statement in the body, so a continue placed before it skips it, and the counter never changes:

PHP
$i = 0;
while ($i < 10) {
    if ($i % 2 === 0) {
        continue;        // skips $i++ below: $i stays 0 forever
    }
    echo $i;
    $i++;
}

This loop never ends. Fix it by updating the counter before any continue, or use a for loop, where the update lives in the header and always runs:

PHP continue in for versus while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Nested loops: break 2 and continue 2

break and continue affect only the innermost loop. In nested loops, add a number to say how many levels to act on: break 2 leaves the inner loop and the loop around it; continue 2 abandons the inner loop and continues with the next iteration of the outer one.

PHP Leaving two loops at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the second loop, continue 2 skips both the remaining seats and the "completely free" message, because it jumps straight to the next row. That message is only reached when the inner loop finishes without finding a taken seat.

The number must be a positive integer literal. break 0 is a compile error ("'break' operator accepts only positive integers"), and so is asking for more levels than exist ("Cannot 'break' 3 levels"). You can't use a variable as the level. A break outside any loop is an error too.

switch counts as a level

For break and continue, a switch statement counts as one loop level. A break inside a switch leaves the switch, not the loop around it. To leave the loop from inside a switch you need break 2, and to continue the loop you need continue 2:

PHP Loop control from inside switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A plain continue in that switch would act like break, and PHP warns about it at compile time, as explained in switch and match. A match expression isn't a loop level, because it's an expression, not a statement.

When you reach for break 3, take it as a hint that the code wants to be split up. Moving the inner loops into a function and using return is usually clearer than counting levels.

goto (and why not)

PHP has a goto statement that jumps to a label elsewhere in the same file or function:

PHP
foreach ($files as $file) {
    if (!is_readable($file)) {
        goto failed;
    }
    // ...
}
echo 'All files OK';
failed:
echo 'Something went wrong';

It comes with restrictions (you can jump out of a loop, but not into one: "'goto' into loop or switch statement is disallowed"), and it makes control flow hard to follow, because a reader has to search for labels to understand where execution goes. Everything goto can do is clearer with break n, return, a function, or an exception. You'll practically never see it in modern PHP code; don't write it.

Early returns and guard clauses

Inside a function, return is the strongest loop control of all: it leaves the loop and the function in one step. Together with continue, it enables a style called guard clauses: check for the cases that end early first, handle them, and leave. The main logic then sits at the outermost level instead of being buried in nested if blocks.

Here is the same validation written both ways:

PHP Nested ifs versus guard clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both functions give the same answers, but in the nested version each error message sits far away from the condition it belongs to, and adding a fourth rule means another level of indentation. In the guard-clause version, every rule is a self-contained three-line block, and you can read the function top to bottom. Functions get their full introduction in the next lesson, Functions.

The same idea applies inside loops, with continue as the guard, exactly like the CSV-style example above. A good rule of thumb: if you're more than two or three levels deep, look for a guard clause or a function to extract.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does for ($i = 1; $i <= 5; $i++) { if ($i === 3) { break; } echo $i; } print?

    When $i is 3, break ends the loop before the echo, so only 1 and 2 are printed.
  2. 2. What does for ($i = 1; $i <= 5; $i++) { if ($i % 2 === 0) { continue; } echo $i; } print?

    continue skips the echo for even numbers, and in a for loop the $i++ update still runs, so the loop goes on to the next value.
  3. 3. You are inside a foreach that is inside another foreach. Which statement stops both loops?

    break 2 leaves the innermost loop and the one around it. continue 2 would continue the outer loop instead of leaving it.
  4. 4. Why can this loop never end? $i = 0; while ($i < 5) { if ($i === 2) { continue; } $i++; }

    In a while loop the update is part of the body. A continue before it skips the increment, so the condition stays true.
  5. 5. Inside a switch that is inside a foreach, what does a plain break; do?

    switch counts as one level for break and continue, so break leaves just the switch. Use break 2 to leave the loop as well.

Summary

  • break leaves the innermost loop immediately; use it to stop searching once you've found something. while (true) loops need a reachable break.
  • continue skips the rest of the current iteration. In for loops the update still runs; in while loops, update the counter before any continue.
  • break n and continue n act on n enclosing levels; the level must be a positive integer literal.
  • switch counts as a level: inside a loop, use break 2 to leave the loop and continue 2 to continue it.
  • Avoid goto; break n, return, functions and exceptions express the same ideas clearly.
  • Guard clauses (early return in functions, continue in loops) handle special cases first and keep the main logic flat.

Next: Functions