PHP Conditional Syntax: Using Switch and Case Statements

Posted March 20, 2004 by Quinn McHenry in PHP programming

The switch/case statement offers similar functionality to the if/elseif statement; however, 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, consider the following if statement:

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

This is identical to the switch/case statement that follows:

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. The resulting output would be as follows:

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. Furthermore, 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 as follows:

One
Two
Other

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.