switch

The 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 many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

The following two examples are two different ways to write the same thing, one using a series of if statements, and the other using the switch statement:

 /* example 1 */
 
 if ($i == 0) {
     print "i equals 0";
 }
 if ($i == 1) {
     print "i equals 1";
 }
 if ($i == 2) {
     print "i equals 2";
 }
 
 /* example 2 */
 
 switch ($i) {
     case 0:
         print "i equals 0";
         break;
     case 1:
         print "i equals 1";
         break;
     case 2:
         print "i equals 2";
         break;
 }
      

It is important to understand how the switch statement is executed in order to avoid messups. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression, PHP begins to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

 /* example 3 */
 
 switch ($i) {
     case 0:
         print "i equals 0";
     case 1:
         print "i equals 1";
     case 2:
         print "i equals 2";
 }
      

Here, if $i equals to 0, PHP would execute all of the print statements! If $i equals to 1, PHP would execute the last two print statements, and only if $i equals to 2, you'd get the 'expected' behavior and only 'i equals 2' would be displayed. So, it's important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

 /* example 4 */
 
 switch ($i) {
     case 0:
         print "i equals 0";
         break;
     case 1:
         print "i equals 1";
         break;
     case 2:
         print "i equals 2";
         break;
     default:
         print "i is not equal to 0, 1 or 2";
 }
      

Another fact worth mentioning is that the case expression may be any expression that evaluates to a scalar type, that is, integer or floating-point numbers and strings. Arrays or objects are meaningless in that context.