Swishy Switch Statements
Posted on 25. Feb, 2010 by admin in Basics
Switch statements are very similar to if statements as they compare a condition, and run code based on weather it is true or false. Unlike if statements which can be used to compare multiple variables and values, switch compares one variable to a bunch of choices. Most likely you will use if statements to compare integers, and switch statements to compare strings.
Lets go back to the same example we used for if statements as see how we do it 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, 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 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.

