PHP Switch Statement

A switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with several different values, and execute a different piece of code depending on which value it equals to. This is what the switch statement is for.

#Syntax
switch (n) {
  case label1:
    code to be executed if n=label1;
    break;
  case label2:
    code to be executed if n=label2;
    break;
  case label3:
    code to be executed if n=label3;
    break;
    ...
  default:
    code to be executed if n is different from all labels;
}

Important points

1. Default is an optional statement. It is also not important that the default should always be the last statement.
2. There can be only one default in a switch statement. More than one default can cause a fatal error.
3. Each case may contain a break statement, which is used to terminate a sequence of statements.
4. The break statement is optional to use in a switch. If break is not used, all statements will be executed after finding the matched case value.
5. PHP allows you to use numbers, characters, strings as well as functions in switch expressions.
6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.

#Example
<?php
$favcolor = "red";
switch ($favcolor) {
  case "red":
    echo "Your favorite color is red!";
    break;
  case "blue":
    echo "Your favorite color is blue!";
    break;
  case "green":
    echo "Your favorite color is green!";
    break;
  default:
    echo "Your favorite color is neither red, blue, nor green!";
}
?>