PHP conditional syntax: using switch and case statements

Contributor Icon Contributed by qmchenry Date Icon March 20, 2004  
Tag Icon Tagged: PHP programming

The switch/case statement offers similar functionality to the if/elseif statement, although it offers a more elegant solution and has capabilities beyond the if/elseif alternative.


A switch/case statement allows multiple comparisons of a varaible. For example, the if statement

if ($var == 1) {
echo "One";
} elseif ($var == 1) {
echo "Two";
} else {
echo "Other";
}

is identical to the switch/case statement:

switch ($var) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
default:
echo "Other";
}

In this example, if $var is equal to 1, the first case statement will be true and the associated code (echo “One”;) will be executed and the resulting output would be:
One
If $var did not match 1 or 2, then the code in the default block would be executed just like the final else block in an if/elseif/else statement.

Switch/case statements differ from if/elseif statements primarily because of the break statement. Without the break statements in the previous example, a value of 1 for $var would match the first case block and every subsequent case block code would be executed until a break statement is encountered, whether or not $var matches the subsequent case statements. The resulting output would be:
One
Two
Other

Previous recipe | Next recipe |
 

 
close Reblog this comment
blog comments powered by Disqus