PHP switch Statement
In this page:
Basic switch Statement
switch compares one variable against a list of fixed candidate values, which reads more cleanly than an equivalent elseif ladder once you're checking more than two or three specific values against the same variable.
Example: Basic switch Statement
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "Start of week";
break;
case "Tuesday":
echo "Second day";
break;
}
?>
Login to try C/C++/Java/PHP code in the editor
The Importance of break
Without an explicit break, execution 'falls through' into the next case's code after a match is found, running it too even though its own condition was never checked — a frequent source of bugs, and the main reason break is treated as mandatory at the end of nearly every case.
Example: The Importance of break
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Monday\n";
case "Tuesday":
echo "Tuesday (falls through!)\n";
break;
}
?>
Login to try C/C++/Java/PHP code in the editor
Default Switch Case
default runs when the tested value doesn't match any listed case — functionally the same role else plays at the end of an elseif ladder, catching whatever wasn't explicitly handled above it.
Example: Default Switch Case
<?php
$fruit = "mango";
switch ($fruit) {
case "apple":
echo "Apple";
break;
default:
echo "Unknown fruit";
}
?>
Login to try C/C++/Java/PHP code in the editor
Grouping Switch Cases
Listing several case labels back-to-back with no code between them, followed by a single shared block, lets multiple distinct values trigger identical behavior without duplicating that block for each one.
Example: Grouping Switch Cases
<?php
$day = "Saturday";
switch ($day) {
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Weekday";
}
?>
Login to try C/C++/Java/PHP code in the editor
Alternative Colon Syntax
Like if, switch supports a colon-based alternative syntax closed with endswitch;, which keeps templates that mix PHP and HTML more readable than the brace-heavy default form would.
Example: Alternative Colon Syntax
<?php
$role = "admin";
switch ($role):
case "admin":
echo "Admin panel";
break;
default:
echo "No access";
endswitch;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: