Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.

What they do

Inside loops (and switch for break):

  • break exits the loop/switch
  • continue skips to the next iteration

Example

<?php

declare(strict_types=1);

foreach (range(0, 5) as $n) {
    if ($n === 2) {
        continue;
    }
    if ($n === 4) {
        break;
    }
    echo $n, "\n";
}

Readability

Use them sparingly—sometimes an extra if keeps flow easier to read.

Exercise

Loop $n from 0 to 5 (inclusive). Skip when $n === 2, break out when $n === 4, otherwise print $n on its own line—output lines 0, 1, 3.

From Zero to PHP — Control flow, functions, arrays, and the web