Learn how to use the switch statement in PHP to simplify complex conditional logic. Includes syntax, code examples, and use cases for beginners and developers.
Syntax:
switch ($variable) {
case 'value1':
// Code to execute if $variable == 'value1'
break;
case 'value2':
// Code to execute if $variable == 'value2'
break;
default:
// Code to execute if $variable doesn't match any case
}
Key points:
==
).break
keyword prevents the code from running into the next case. Omitting break
can lead to unintended fall-through behavior.default
case is executed if no matching case is found. It’s good practice to include it to handle unexpected values.(W3Schools.com, DEV Community, Stack Overflow)Example:
$day = 'Monday';
switch ($day) {
case 'Monday':
echo "Start of the work week.";
break;
case 'Friday':
echo "End of the work week.";
break;
default:
echo "Midweek days.";
}
In this example, if $day
is ‘Monday’, it will output “Start of the work week.” If it’s ‘Friday’, it will output “End of the work week.” For any other value, it will output “Midweek days.”(Wikipedia)
Best Practices:
break
Statements: Always include break
statements to prevent fall-through unless intentionally desired.default
case to handle unexpected values.The statement list for a case can also be empty, which simply passes control into the statement list for the next case.
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>
Explanation: To understand how this example works in detail, see Switch-Case Example in PHP: Handling Multiple Cases Together.
A special case is the default case. This case matches anything that wasn’t matched by the other cases. For example:
<?php
$i = 1
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP - Switch</title>
</head>
<body>
<h1>PHP - Switch</h1>
<?php
$favcolor = "blue";
echo "<h2>My favorite color is " . $favcolor . "</h2>";
switch ($favcolor) {
case "red":
echo "<h2 style='color:" . $favcolor . "'>Your favorite color is red!</h2>";
break;
case "blue":
echo "<h2 style='color:" . $favcolor . "'>Your favorite color is blue!</h2>";
break;
case "green":
echo "<h2 style='color:" . $favcolor . "'>Your favorite color is green!</h2>";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>
For more detailed information, refer to the PHP Manual on switch statements.