PHP Switch

switch's loose comparison trap, fallthrough, and PHP 8's match expression.

Beginner
Key Points`switch` compares loosely and falls through — a missing `break` keeps executing.

基本用法

PHP
<?php
$color = "blue";

switch ($color) {
    case "red":
        echo "红色\n";
        break;
    case "blue":
    case "cyan":
        echo "蓝色系\n";
        break;
    default:
        echo "未知\n";
}
Output
蓝色系

To share a block across cases, leave earlier cases empty so execution falls through — the only legitimate use of fallthrough.

忘记 break 的后果

PHP
<?php
$n = 2;

switch ($n) {
    case 1:
        echo "一\n";
    case 2:
        echo "二\n";
    case 3:
        echo "三\n";
        break;
    default:
        echo "其它\n";
}
Output
二
三
After matching case 2 it keeps running case 3. Such bugs are nearly invisible in review — **every case needs break or return** unless fallthrough is intentional.

松散比较的坑

PHP
<?php
switch ("1abc") {
    case 1:
        echo "命中 1\n";
        break;
    default:
        echo "未命中\n";
}
Output
未命中

Before PHP 8, "1abc" == 1 was true and this matched case 1. PHP 8 compares a non-numeric string with a number as strings, so it no longer matches.

switch always uses ==, never ===. For strict matching use match (PHP 8) or an if / elseif chain.

match 表达式

PHP 8's match is an expression with a return value, compares strictly, and must be exhaustive (otherwise UnhandledMatchError).

PHP
<?php
$color = "blue";

$msg = match ($color) {
    "red" => "红色",
    "blue", "cyan" => "蓝色系",
    default => "未知",
};
echo $msg, "\n";

// 严格比较:0 和 "0" 不是同一个分支
$v = 0;
echo match ($v) {
    0 => "整数零",
    "0" => "字符串零",
}, "\n";

// 分支可以写表达式
$score = 85;
$grade = match (true) {
    $score >= 90 => "A",
    $score >= 80 => "B",
    default => "C",
};
echo $grade, "\n";
Output
蓝色系
整数零
B
Featureswitchmatch
Is an expression否(语句)是,有返回值
Comparison松散 ==严格 ===
Fallthrough会不会
Must be exhaustive否,可省略 default是,否则抛错
Multiple values多个 case 堆叠逗号分隔

In new code match largely replaces switch. No need to rewrite old code, but prefer match for new branching logic.

Friends & Partners