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.

switch (n) {
  case label1:
    code to be executed if n=label1;
  case label2:
    code to be executed if n=label2;
  case label3:
    code to be executed if n=label3;
    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.

$favcolor = "red";
switch ($favcolor) {
  case "red":
    echo "Your favorite color is red!";
  case "blue":
    echo "Your favorite color is blue!";
  case "green":
    echo "Your favorite color is green!";
    echo "Your favorite color is neither red, blue, nor green!";