Certified PHP Developer Learning Resources Switch

Switch
 


Switch statements work the same as if statements. However the difference is that they can check for multiple values. Of course you do the same with multiple if..else statements, but this is not always the best approach.

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. The syntax for the switch statement as follows:

switch (expression) {
   case label_1:
      statements_1
      [break;]
   case label_2:
      statements_2
      [break;]
   ...
   default:
     statements_n
     [break;]
}

The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. Use break to prevent the code from running into the next case automatically.

 For Support