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.
switch ($day) { case "sat": case "sun": echo "Weekend"; break; default: echo "Weekday"; }
Try it
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.
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
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.
switchuses==. With PHP 8 semantics0 == "a"is false, but"1" == "01"andnull == ""are still true. When types matter, usematch, which compares strictly. - Always end cases deliberately. Use
break,returnorcontinue 2(inside a loop). Mark intentional fall-through with a comment. - Empty cases stack. Several
caselabels in a row share one block. breakandcontinuein a loop. Insideswitch,breakleaves the switch only andcontinueacts likebreak. To affect an enclosing loop usebreak 2orcontinue 2. PHP 7.3+ warns about a barecontinueinside a switch. See break and continue.defaultis optional, but without it an unmatched value silently does nothing.switch (true)is a known idiom for range tests, thoughif/elseifis usually clearer.- Alternative syntax:
switch (...): ... endswitch;exists for templates. Only whitespace is allowed betweenswitch (...):and the firstcase. - Evaluation order. Case expressions are evaluated lazily, only until one matches.