PHP Switch Statement

PHP Switch Statement

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.

1 - Switch Syntax

switch (expression) {
    case value1:
        // code to execute
        break;
    case value2:
        // code to execute
        break;
    default:
        // default code
}

2 - How It Works

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.

3 - Example

$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.";
}

4 - PHP 8 Match Expression

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;

Note: Unlike switch, the match expression uses strict comparison (===) and throws an UnhandledMatchError if no arm matches and there is no default.

-Tip-