The PHP switch Statement

The switch statement in PHP is a control structure used to evaluate a single value against a set of multiple possible conditions, and execute different code blocks depending on which condition matches the value.

The syntax of a switch statement in PHP is as follows:

switch (expression) {
  case value1:
    // Code to be executed when expression matches value1
    break;
  case value2:
    // Code to be executed when expression matches value2
    break;
  ...
  default:
    // Code to be executed when none of the previous cases match
    break;
}

Here, expression is the value to be evaluated and the case statements specify the values that expression can match. If expression matches a case value, the code block following that case statement is executed. The break statement is used to end the current case and move on to the next statement.

If expression does not match any of the case values, the code block following the default statement is executed. The default statement is optional, and is executed only when none of the previous case statements match.

Here’s an example of using the switch statement in PHP:

$num = 3;

switch ($num) {
  case 1:
    echo "The number is 1";
    break;
  case 2:
    echo "The number is 2";
    break;
  case 3:
    echo "The number is 3";
    break;
  default:
    echo "The number is not 1, 2, or 3";
    break;
}

In this example, the value of $num is evaluated against three possible cases. Since $num is equal to 3, the code block following the case 3 statement is executed, which outputs “The number is 3”. The break statement is used to end the case 3 statement and prevent the code from executing the default statement.

The switch statement can be a useful alternative to a series of if statements when evaluating a single value against multiple possible conditions. It can make your code more concise and easier to read, especially when dealing with a large number of conditions.

Scroll to Top