switch
Use switch when you're comparing one value against many possibilities.
PHP
<?php
$day = "Sun";
switch ($day) {
case "Sat":
case "Sun":
echo "Weekend";
break;
case "Mon":
echo "Start of the week";
break;
default:
echo "Midweek";
}break is mandatory. Without it, execution "falls through" into the
next case — occasionally useful (as with Sat/Sun above), usually a
bug.
switch uses loose (==) comparison, which can surprise you:
PHP
<?php
switch ("1abc") {
case 1: echo "matched 1!"; break; // PHP 7 matched here
default: echo "default"; // PHP 8 lands here
}match (PHP 8+)
match is the modern replacement: it uses strict comparison, needs
no break, and returns a value.
PHP
<?php
$status = 'paid';
$label = match ($status) {
'new' => 'Awaiting payment',
'paid' => 'Payment received',
'shipped' => 'On the way',
'cancelled' => 'Cancelled',
default => 'Unknown',
};
echo $label; // Payment receivedSeveral values can share a result:
PHP
<?php
$type = match ($code) {
200, 201, 204 => 'success',
400, 404 => 'client error',
500, 502 => 'server error',
default => 'other',
};Unlike switch, a match with no matching arm and no default throws
an UnhandledMatchError — which is usually what you want, because
silently doing nothing hides bugs.
Prefer match for new code; you'll still meet switch everywhere in
existing projects.