Swishy Switch Statements

Posted on 25. Feb, 2010 by admin in Basics


Switch statements are very similar to if statements since both compare a condition and run code based on whether it is true or false. Unlike if statements which can be used to compare multiple variables and values, switch statements compare one variable  to a number of choices. Most likely you will use if statements to compare integers, and switch statements to compare strings.

Let’s go back to the same example we used for if statements to see how we complete an output for switch:


<?php
//Color of Stoplight
$stopLight = "Green";

//Switch statement
switch ($stopLight)
{
case "Red":
echo "Stop!";
break;

case "Yellow":
echo "Slow down...";
break;

case "Green":
echo "Floor it!";
break;
}

?>

Output:

Floor it!

There are several differences from our if statement syntax. The variable we want to test still goes inside the parentheses, but you do not put anything else. All the strings or numbers you want to compare it with go after case inside the {}. Notice also that you need to use break to end the code to run if the statement is true. Now, this is almost the same as our other if statement, but it is missing one thing. What happens if the light is not red, yellow, or green?


<?php
//Color of Stoplight
$stopLight = "Purple";

//Switch statement
switch ($stopLight)
{
case "Red":
echo "Stop!";
break;

case "Yellow":
echo "Slow down...";
break;

case "Green":
echo "Floor it!";
break;

default:
echo "The stoplight must be broken.";
break;

}

?>

Output:

The stoplight must be broken.

Just as we used the else statement to tell PHP what to do if none of the statements are true, we use the default statement in switch. As you can see, both can do the same thing, it is up to you to choose which one you want to use in your code.