PHP Switch Statement
The switch statement is used to perform different actions based on different possible values of a single variable, avoiding long chains of elseif statements. Each possible value is a case.
Each case should typically end with a break statement to prevent execution from falling through to the next case. A default case can be included to run when no other case matches.
switch ($var) {
case value1:
// code
break;
default:
// code
}How switch works
PHP compares the switch expression against each case value using loose comparison. When a match is found, PHP runs the code for that case until it hits a break or the end of the switch block.
The default case
default runs when none of the case values match the expression, similar to a final else in an if/elseif chain.
<?php
$day = "Mon";
switch ($day) {
case "Mon":
echo "Monday";
break;
default:
echo "Another day";
}
?>MondaySince $day matches "Mon", that case runs and break stops further checks.
<?php
$grade = "F";
switch ($grade) {
case "A":
case "B":
echo "Good job";
break;
default:
echo "Keep trying";
}
?>Keep tryingSince $grade doesn't match A or B, execution falls to the default case.
Key points
- switch compares one expression against multiple case values.
- break prevents falling through to the next case.
- default runs when no case matches.
- Multiple case labels can share the same block of code.
