Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

PHP switch statement

Reference for PHP switch: multi-way branching with loose comparison, break and fall-through, default, continue behavior and when to use match instead.

switch compares one value against a list of case labels and runs the code from the first matching label onward. It is a neat alternative to a long if/elseif chain when you test a single value for equality.

Two details cause most bugs. The comparison is loose (==), and execution continues into the next case unless you stop it with break (or return). That fall-through is sometimes useful and often accidental.

PHP
switch ($day) {
    case "sat":
    case "sun":
        echo "Weekend";
        break;
    default:
        echo "Weekday";
}

Try it

PHP Fall-through and default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Loose comparison pitfalls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
switch (expression) {
    case value1:
        // ...
        break;
    case value2:
    case value3:
        // ...
        break;
    default:
        // ...
}
Name Description
expression Evaluated once. Its value is compared with each case value using ==.
case value Any expression. Cases are tested in order, top to bottom.
default Optional. Runs when no case matches. It may appear anywhere, but the last position is conventional.

Return value: none; switch is a statement.

Usage notes

  • Loose comparison. switch uses ==. With PHP 8 semantics 0 == "a" is false, but "1" == "01" and null == "" are still true. When types matter, use match, which compares strictly.
  • Always end cases deliberately. Use break, return or continue 2 (inside a loop). Mark intentional fall-through with a comment.
  • Empty cases stack. Several case labels in a row share one block.
  • break and continue in a loop. Inside switch, break leaves the switch only and continue acts like break. To affect an enclosing loop use break 2 or continue 2. PHP 7.3+ warns about a bare continue inside a switch. See break and continue.
  • default is optional, but without it an unmatched value silently does nothing.
  • switch (true) is a known idiom for range tests, though if/elseif is usually clearer.
  • Alternative syntax: switch (...): ... endswitch; exists for templates. Only whitespace is allowed between switch (...): and the first case.
  • Evaluation order. Case expressions are evaluated lazily, only until one matches.