Forum und email

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.

Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

Note: Note that switch/case does loose comparision.

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

Example#1 switch structure

<?php
if ($i == 0) {
    echo 
"i equals 0";
} elseif (
$i == 1) {
    echo 
"i equals 1";
} elseif (
$i == 2) {
    echo 
"i equals 2";
}

switch (
$i) {
case 
0:
    echo 
"i equals 0";
    break;
case 
1:
    echo 
"i equals 1";
    break;
case 
2:
    echo 
"i equals 2";
    break;
}
?>

Example#2 switch structure allows usage of strings

<?php
switch ($i) {
case 
"apple":
    echo 
"i is apple";
    break;
case 
"bar":
    echo 
"i is bar";
    break;
case 
"cake":
    echo 
"i is cake";
    break;
}
?>

It is important to understand how the switch statement is executed in order to avoid mistakes. 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 does PHP begin 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: