PHP Switch
switch compares one value against many cases. Cases fall through unless you break — that's the classic source of bugs.
Basic shape
PHP
switch ($status) {
case 'paid':
echo 'OK';
break;
case 'pending':
echo 'Awaiting';
break;
case 'refunded':
echo 'Refund issued';
break;
default:
echo 'Unknown';
}
Fall-through
PHP
switch ($day) {
case 'Sat':
case 'Sun':
echo 'weekend';
break;
default:
echo 'weekday';
}
Stacking case labels without a break in between means they all run the same body. Missing a break by accident is a bug — be deliberate.
Loose comparison gotcha
switch uses == (loose) for matching. switch(0) matches case 'whatever': in PHP < 8.0. Modern PHP fixed many of these surprises, but…
Prefer match (8.0+)
match is the modern replacement — strict comparison, expression-based, no fall-through:
PHP
echo match ($status) {
'paid' => 'OK',
'pending' => 'Awaiting',
'refunded' => 'Refund issued',
default => 'Unknown',
};
Tip: For new code, default to
match. Save switch for cases that need fall-through or multi-statement bodies.Example
Example
<?php
$status = 'paid';
switch ($status) {
case 'paid': echo 'OK'; break;
case 'pending': echo 'Awaiting'; break;
default: echo 'Unknown';
}
Try it Yourself »
Exercise
Without this keyword cases fall through.
case 'paid': echo 'OK';
;
Five letters.
Discussion
Loading…