Switch Case in PHP: A Small Code Example

Quick Summary
- A PHP switch compares one value against a list of cases and runs the first match, a tidier option than long if/elseif chains.
- End each case with break to avoid fall-through, and use the optional default case for values that match nothing.
- Cases use loose comparison, not strict, which matters when switching on strings that start with a number.
A switch case in PHP compares one value against a list of cases and runs the code of the first one that matches. It’s a tidier alternative to a long if/elseif chain when you check the same variable again and again.
The basic syntax
switch (variable) {
case 'value':
# code...
break;
default:
# code...
break;
}Replace variable with the value you want to test and 'value' with what to compare it against. Add as many case blocks as you need.
- Each
caseis compared with loose comparison (==), not strict comparison (===). That matters when you switch on strings that start with a number. breakends the switch. Without it, PHP keeps running the code of the following cases as well, which is called fall-through.defaultruns when no case matches. It’s optional.
Example: even or odd
$n = 12;
$r = $n % 2;
switch ($r) {
case 0:
echo "{$n} is an even number \n";
break;
default:
echo "{$n} is an odd number";
break;
}$n % 2 gives the remainder of dividing $n by 2. A remainder of 0 means the number is even; any other value is handled by default, which reports an odd number. With $n = 12 it prints 12 is an even number. The curly braces in "{$n} is an even number" insert the variable into the double-quoted string. Single-quoted strings don’t do this, as the PHP string basics show.
Example: a message for each day
switch (date('l')) {
case "Monday":
echo "PHP on Monday";
break;
case "Tuesday":
echo "Angular on Tuesday";
break;
case "Wednesday":
echo "Python on Wednesday";
break;
case "Thursday":
echo "Node on Thursday";
break;
case "Friday":
echo "Laravel on Friday";
break;
case "Saturday":
echo "WordPress on Saturday";
break;
case "Sunday":
echo "React js on Sunday";
break;
default:
echo "I don't know what day it is";
break;
}date('l') returns the full English name of the current weekday, such as Monday, based on PHP’s default timezone setting. The switch prints a different message for each of the seven days. Because date('l') always returns one of those names, the default case is only a safety net here.
Related articles
- the PHP ternary operator: a one-line choice between two values

