Control flow and match

PHP · Essentials · 10 min

Every program needs decisions and loops, and match is the modern, safer replacement for most switch statements.

if, elseif and else work as in C-family languages. The ternary $a ? $b : $c and the short form $a ?: $b (use $a if truthy, else $b) cover small cases.

match (PHP 8.0) is an expression that returns a value:

$label = match ($status) {
    200, 201 => 'ok',
    404 => 'not found',
    default => 'error',
};

Unlike switch, match compares with ===, never falls through, and throws an UnhandledMatchError when no arm matches and there is no default. Use match (true) to test a series of conditions.

Loops:

  • for ($i = 0; $i < 3; $i++) for counting.
  • while (cond) and do { } while (cond) for open-ended repetition.
  • foreach ($items as $item) or foreach ($map as $key => $value) for arrays and iterables. This is the loop you will use most.
  • break leaves a loop, continue skips to the next iteration; both take an optional number to affect outer loops (break 2).

switch still exists and uses loose == comparison, which is one more reason to prefer match in new code.

Example

<?php
$scores = ['ana' => 91, 'ben' => 67, 'cy' => 78];

foreach ($scores as $name => $score) {
    $grade = match (true) {
        $score >= 90 => 'A',
        $score >= 75 => 'B',
        default => 'C',
    };
    echo "$name: $grade\n";
}
// ana: A
// ben: C
// cy: B

for ($i = 1; $i <= 10; $i++) {
    if ($i % 2) continue;   // skip odd numbers
    if ($i > 6) break;
    echo $i, " ";           // 2 4 6
}
echo "\n";

Remember

  • match is an expression with strict comparison and no fall-through
  • match(true) replaces long if/elseif chains
  • foreach ($array as $key => $value) is the everyday loop

Watch out for

  • Forgetting default in a match whose subject can take unexpected values, causing UnhandledMatchError.

Check yourself

  1. What happens when match ('1') { 1 => 'one' } runs?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.php.net/manual/en/control-structures.match.php