PHP Switch
The switch statement compares one value against a list of possible cases, offering a clean alternative to a long chain of if...elseif tests.
When to use a switch
When you need to compare a single variable against many possible values, a long elseif chain can become repetitive and hard to scan. The switch statement is built for exactly this situation. You give it one expression, and it checks that expression against a series of case labels, running the block that matches. It reads clearly and signals to anyone reading the code that all the branches are testing the same value.
A basic switch
<?php
$day = "Wed";
switch ($day) {
case "Mon":
echo "Start of the work week.";
break;
case "Wed":
echo "Midweek already.";
break;
case "Fri":
echo "Almost the weekend.";
break;
default:
echo "Just another day.";
}
?>Anatomy of the statement
- switch (expression) — the value that PHP evaluates once and then compares against each case.
- case value: — a label; if the expression matches this value, execution begins here.
- break; — stops the switch and jumps past the closing brace, preventing the next case from running.
- default: — an optional catch-all block that runs when no case matches; it is good practice to always include one.
Deliberate fall-through
You can leave out break on purpose to let several cases share the same block. By stacking case labels with no code between them, every listed value runs the same statements. This is a tidy way to group values that should be treated identically, such as grouping weekend days together.
Grouping cases
<?php
$day = "Sun";
switch ($day) {
case "Sat":
case "Sun":
echo "It is the weekend, enjoy your rest.";
break;
default:
echo "It is a weekday, back to work.";
}
?>How switch compares values
A switch uses loose comparison, the same kind as the == operator, so the value and each case are compared without checking their types strictly. That is fine for straightforward strings and integers, but it means a case can match a value of a different type. When you need strict, type-aware matching, modern PHP offers the match expression as a safer, more compact option.
The match expression alternative
<?php
$statusCode = 404;
$message = match ($statusCode) {
200, 201 => "Success",
301, 302 => "Redirect",
404 => "Not Found",
500 => "Server Error",
default => "Unknown status",
};
echo $message; // Not Found
?>Exercise: PHP Switch
What comparison does PHP's switch statement use to match cases?