PHP & MySQL
PHP switch-case Statement - Syntax & Examples
Complete guide to the PHP switch statement - syntax, fall-through behavior, strict vs loose comparison, match expression alternative, and practical use cases.
Basic Syntax
<?php
$day = 'Tuesday';
switch ($day) {
case 'Monday':
echo 'Start of the work week';
break;
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
echo 'Midweek';
break;
case 'Friday':
echo 'Almost weekend!';
break;
case 'Saturday':
case 'Sunday':
echo 'Weekend!';
break;
default:
echo 'Invalid day';
break;
}
// Output: Midweek
How switch Works
PHP evaluates the switch expression once, then compares it against each case value using loose comparison (==). Execution continues from the matching case until a break is encountered.
Fall-Through Behavior
<?php
$grade = 'B';
// WITHOUT break - falls through to next case
switch ($grade) {
case 'A':
echo 'Excellent ';
case 'B':
echo 'Good ';
case 'C':
echo 'Average ';
default:
echo 'Need improvement';
}
// Output: Good Average Need improvement
// (all cases after 'B' execute because no break!)
// WITH break - correct behavior
switch ($grade) {
case 'A':
echo 'Excellent';
break;
case 'B':
echo 'Good';
break;
case 'C':
echo 'Average';
break;
default:
echo 'Need improvement';
}
Loose Comparison Warning
<?php
// switch uses == (loose), NOT === (strict)
$value = 0;
switch ($value) {
case 'hello':
echo 'Matched string!'; // THIS EXECUTES!
break; // Because 0 == 'hello' is true
case 0:
echo 'Matched zero';
break;
}
// Output: Matched string! (unexpected!)
// Solution: use match() in PHP 8.0+ for strict comparison
match Expression (PHP 8.0+)
<?php
// match uses strict comparison (===) and returns a value
$status = match($code) {
200 => 'OK',
301 => 'Redirect',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown',
};
echo $status; // "OK" if $code is 200
// match with multiple conditions
$category = match(true) {
$age < 13 => 'child',
$age < 18 => 'teenager',
$age < 65 => 'adult',
default => 'senior',
};
switch vs if-else vs match
| Feature | switch | if-elseif | match (8.0+) |
|---|---|---|---|
| Comparison | Loose (==) | Any expression | Strict (===) |
| Returns value | No | No | Yes |
| Fall-through | Yes (needs break) | No | No |
| Best for | Multiple exact values | Complex conditions | Value mapping |
Last updated: 2026 • Browse all courses