switch is the older way to compare one value against many options. You will see it a lot in existing code, so you should know how it works.
<?php
$day = "Tue";
switch ($day) {
case "Mon":
echo "Start of the week";
break;
case "Tue":
case "Wed":
echo "Midweek";
break;
case "Sat":
case "Sun":
echo "Weekend";
break;
default:
echo "Another day";
}
Midweek
The break statement
Each case needs a break. Without it, PHP keeps running the next case’s code too. That is called fall-through.
<?php
$n = 1;
switch ($n) {
case 1:
echo "one ";
case 2:
echo "two ";
break;
case 3:
echo "three";
}
one two
case 1 had no break, so PHP ran into case 2. Sometimes this is intended (like "Tue" and "Wed" above), but it is a common source of bugs.
The default case
default runs when no case matches. It is optional, and usually goes last.
Loose comparison
switch compares with ==, not ===. Strings that look like numbers can match unexpectedly.
<?php
$input = "1";
switch ($input) {
case 1:
echo "matched the integer 1";
break;
default:
echo "no match";
}
matched the integer 1
switch vs match
switch | match | |
|---|---|---|
| Comparison | Loose (==) | Strict (===) |
| Returns a value | No | Yes |
Needs break | Yes | No |
| Fall-through | Yes | No |
| No match | Silently does nothing | UnhandledMatchError |
| Runs several statements | Yes | One expression per arm |
When switch is still the right tool
Use switch when each branch needs several statements, or when you work on PHP 7. Otherwise match is safer.
Forgetting break
break. Your editor may warn you. Always check each case ends with break, return or a comment saying the fall-through is on purpose.