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)anddo { } while (cond)for open-ended repetition.foreach ($items as $item)orforeach ($map as $key => $value)for arrays and iterables. This is the loop you will use most.breakleaves a loop,continueskips 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.