PHP : switch Statement

In PHP, the switch statement is used as an alternative to if...elseif...else statements when you need to compare a single variable against multiple possible values. It provides a concise way to execute different blocks of code based on the value of a variable. Here's the basic syntax of the switch statement:


switch (variable) {
    case value1:
        // Code to be executed if variable equals value1
        break;
    case value2:
        // Code to be executed if variable equals value2
        break;
    // Additional cases...
    default:
        // Code to be executed if none of the cases match
        break;
}

 

  • variable: The variable whose value you want to compare.
  • value1, value2, etc.: The possible values that variable can take.
  • case: Specifies a value to match against variable.
  • default: Specifies the code to be executed if none of the cases match.

Each case block represents a possible value of the variable. If the value of variable matches the value specified in a case block, the corresponding block of code is executed. The break statement terminates the switch statement and prevents fall-through to the next case. The default case is optional and executed if none of the cases match.

Here's an example of a switch statement in PHP:


$day = "Monday";

switch ($day) {
    case "Monday":
        echo "Today is Monday.";
        break;
    case "Tuesday":
        echo "Today is Tuesday.";
        break;
    default:
        echo "Today is not Monday or Tuesday.";
        break;
}

 

In this example:

  • If the value of $day is Monday, it outputs Today is Monday.
  • If the value of $day is Tuesday, it outputs Today is Tuesday.
  • If the value of $day is any other value, it outputs Today is not Monday or Tuesday.