PHP Tutorial · Control Flow · Lesson 15 of 38
PHP Switch and Match
Compare one value against many with switch and the PHP 8 match expression.
switch
switch compares with loose equality (==) and needs break after each case:
<?php
$day = "Sat";
switch ($day) {
case "Sat":
case "Sun":
echo "Weekend\n";
break;
case "Fri":
echo "Almost weekend\n";
break;
default:
echo "Weekday\n";
}
Output
Weekend
match (PHP 8)
match is the modern replacement. It's an expression (it returns a value), uses strict comparison (===), needs no break, and throws UnhandledMatchError if nothing matches and there's no default:
<?php
$status = 404;
$message = match ($status) {
200, 201 => "Success",
301, 302 => "Redirect",
404 => "Not found",
default => "Unknown",
};
echo $message, "\n";
Output
Not found
match (true) is a neat way to write a chain of conditions:
<?php
$bmi = 23.4;
$category = match (true) {
$bmi < 18.5 => "Underweight",
$bmi < 25 => "Normal",
$bmi < 30 => "Overweight",
default => "Obese",
};
echo $category, "\n";
Output
Normal
Test yourself
Which comparison does match use?
Loose (==)Strict (===)Spaceship (<=>)It depends on the type
Show answer
Answer: Strict (===)