switch
When one variable has to be compared with several values, a chain of if and elseif gets long. The switch statement writes such a choice more compactly.
A simple switch
The value goes in parentheses, and each branch starts with the word case:
<?php
$day = 3;
switch ($day) {
case 1:
echo 'Monday';
break;
case 3:
echo 'Wednesday';
break;
}PHP finds the branch with the matching value and runs its code.
The default branch
If no option matched, the default branch runs:
<?php
$color = 'purple';
switch ($color) {
case 'red':
echo 'Stop';
break;
case 'green':
echo 'Go';
break;
default:
echo 'Unknown signal';
}Why break is needed
break ends the switch. Without it, execution "falls through" into the next branch:
<?php
$level = 1;
switch ($level) {
case 1:
echo 'one ';
case 2:
echo 'two ';
break;
case 3:
echo 'three';
}This prints "one two": the first branch has no break, so the second one ran too.
Several values, one branch
Fall-through is used on purpose to handle several values with the same code:
<?php
$day = 6;
switch ($day) {
case 6:
case 7:
echo 'Weekend';
break;
default:
echo 'Working day';
}switch or match
The match expression from the lesson on conditions solves the same task and returns a value:
<?php
$day = 6;
$type = match ($day) {
6, 7 => 'Weekend',
default => 'Working day',
};
echo $type; // Weekendswitch | match | |
|---|---|---|
| Comparison | Loose, like == | Strict, like === |
break | Needed in every branch | Not needed |
| Result | None, it is a statement | Returns a value |
| Several lines in a branch | Yes | No, a single expression |
When you need to pick a value, use match. When a branch has several actions, use switch.
Common mistake
switch compares loosely. The string '1' and the number 1 are equal to it, and the first matching branch wins:
<?php
$value = '1';
switch ($value) {
case 1:
echo 'the number one';
break;
case '1':
echo 'the string one';
break;
}This prints "the number one". If the type matters, use match.