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:

Example 1Try it yourself
<?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:

Example 2Try it yourself
<?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:

Example 3Try it yourself
<?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?

  1. Loose (==)
  2. Strict (===)
  3. Spaceship (<=>)
  4. It depends on the type
Show answer

Answer: Strict (===)