The switch statement is used to perform different actions based on different conditions. It is an alternative to using a long chain of if...elseif...else statements.
switch (expression) {
case value1:
// code to execute
break;
case value2:
// code to execute
break;
default:
// default code
}
The switch expression is evaluated once and compared to each case value. When a match is found, the block of code runs until a break is reached. The default case runs if no match is found.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Friday":
echo "End of the work week!";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "Midweek day.";
}
PHP 8 introduced match as a cleaner, stricter alternative to switch:
$result = match ($day) {
"Monday" => "Start of the work week!",
"Friday" => "End of the work week!",
"Saturday", "Sunday" => "It's the weekend!",
default => "Midweek day."
};
echo $result;