Switch in PHP

In PHP, the switch statement provides a way to execute one of several blocks of code based on the value of a variable or an expression. It's an alternative to using multiple if statements when you need to compare a variable or expression against multiple values. The basic syntax of a switch statement is as follows:

switch (expression) {
    case value1:
        // Code to be executed if expression matches value1
        break;
    case value2:
        // Code to be executed if expression matches value2
        break;
    // Additional cases as needed
    default:
        // Code to be executed if expression does not match any case
}

Here's what each part of the switch statement does:

  • Expression: This is the variable or expression that is being tested against multiple values.
  • Case: Each case statement specifies a value that the expression is compared against. If the expression matches the value specified in a case, the corresponding block of code is executed.
  • Break: The break statement is used to terminate the switch statement and exit the switch block. If omitted, the code execution will continue to the next case, regardless of whether the condition is met.
  • Default: The default case is optional and executes when none of the case values match the expression. It's similar to the else statement in an if-else structure.
$day = "Monday";

    switch ($day) {
        case "Monday":
            echo "Today is Monday.";
            break;
        case "Tuesday":
            echo "Today is Tuesday.";
            break;
        case "Wednesday":
            echo "Today is Wednesday.";
            break;
        // More cases as needed
        default:
            echo "Today is not a weekday.";
    }

In this example, if the value of $day is "Monday", "Tuesday", or "Wednesday", the corresponding message will be echoed. If $day does not match any of these values, the default message "Today is not a weekday." will be echoed.

Next Article ❯