The switch statement
Learn multi-way selection with switch, case, break and default.
The switch statement
To branch on many possible values of a single variable, use switch. You write switch ($day) and list each possible value with case. Code runs from the matching case onward.
Key detail: without a break; at the end of a case, PHP falls through to the next case (called fall-through). When no case matches, default runs.
break and fall-through
When a case matches, PHP starts running code from that point. When it sees break; it exits the switch. Without break; the code of later cases also runs; this is called fall-through.
Sometimes fall-through is what you want (for example two values producing the same output). But most of the time you put a break; in each case to prevent unintended execution.
Exercise Print the day name
The $day variable is already declared. Write a switch: for case 1 print 'Monday', for case 2 print 'Tuesday', for default print 'Unknown'. Put a break; at the end of each case.
Show example solution
... break; structure.
Example solution:
<?php
$day = 1;
// Day name
switch ($day) {
case 1:
echo 'Monday';
break;
case 2:
echo 'Tuesday';
break;
default:
echo 'Unknown';
}
Test yourself
-
What is the switch output?
$color = 'red'; switch ($color) { case 'blue': echo 'sky'; break; case 'green': echo 'grass'; break; default: echo 'unknown'; }- sky
- grass
- red
- unknown
Show answer
unknown — Correct. 'red' is not in the case list, so default runs.
-
Write the break keyword
$n = 2; switch ($n) { case 1: echo 'one'; ____; case 2: echo 'two'; break; }Show answer
$n = 2; switch ($n) { case 1: echo 'one'; break; case 2: echo 'two'; break; } -
Match the switch parts
- switch
- Branching statement
- case
- Possible value
- break
- Exit command
- default
- Catcher branch