PHP Switch statements are another way of doing something similar to using If, Else, and Elseif Statements. You don’t ever have to use switch statements if you’re comfortable with If statements, but it’s nice to know how.
The Switch statement tests the value of something (usually a variable), looks for the “case” when it is true, and executes the command within the true case. Let’s take a look at an example, be sure to read the comments:
<?php $var1 = 10; // Let's make PHP echo out a specific string, based on the number found in the $var1 variable switch ($var1) { case 5: // If $var1 is equal to 5... echo "We have the number 5!"; break; // After every case, we need to insert a "break" or PHP // will keep looking at other cases, which we usually don't want it to do case 10: // If $var2 is equal to 10, which it is... echo "We have 10! Woo hoo!"; break; case 15: // If $var1 is equal to 15... echo "Oh 15, how I missed you so."; break; default: // The "default" case is optional. If PHP can not find a true case, it will use the default. echo "What is PHP again?"; break; } ?>
So instead of using a bunch of If statements, we just used some switches. This can potentially be easier to read than many If statements, but either way will work. It’s up to you. This is how it would look if we used If statements:
<?php $var1 = 10; if ($var1 == 5) { echo "We have the number 5!"; } elseif ($var1 == 10) { echo "We have 10! Woo hoo!"; } elseif ($var1 == 15) { echo "Oh 15, how I missed you so."; } else { echo "What is PHP again?"; } ?>
Go back to Building PHP Scripts.
Tags: php, programming, statements, switch, tutorial