The switch statement is used to perform different actions based on different conditions. It is an alternative to multiple if-elseif statements.
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Tuesday":
echo "Second day of the week.";
break;
case "Wednesday":
echo "Mid-week day.";
break;
case "Thursday":
echo "Almost weekend!";
break;
case "Friday":
echo "Weekend starts tomorrow!";
break;
default:
echo "Weekend!";
}
?>
👉 Explanation:
switch compares a variable with multiple values.case defines each possible match.break is important — it stops the switch from executing the next cases.default executes when no case matches.<?php
$num = 2;
switch ($num) {
case 1:
echo "One";
case 2:
echo "Two"; // This will also run because break is missing above
break;
case 3:
echo "Three";
break;
}
?>
👉 Note:
If you don't use break, PHP will continue executing the next cases (called "fall-through").