In our last class we covered if, else, and elseif statements, which is one of the ways to create a decision making process for your page.
In the this class, we'll learn about the switch function, and how it can be used instead of an if/else condition.
A switch statement is typically used for large if/else statements. If you have a variable that could be one of ten different foods, writing all that if/elseif/else could become pretty monotonous. Here's what the syntax for a switch statement looks like:
case 1: // if its a string, it needs the quotes
echo "This is the first case";
echo "This is executed if $x = 'Bob'";
echo "Something else";
Let's take a close look.
switch($x) starts our statement. $x can be any variable. An integer or a string.
Curly brakcet to open the switch statement so PHP knows what to look at.
case 1: is our first case. This is the same as writing a quick if statement that could be true. If it is true, case 1:'s code underneath will be executed, and case "Bob" and default will be ignored.
case "Bob": is the same as case 1, but we used a string instead.
default: is if all the case's are returned false. It's the safety net.
We also use break; after each case, even in default. the break; command tells PHP that's the end of the switch and should exit it now and continue on with the rest of the page, instead of executing all the other cases.
Keep an open eye for some sneaky characters. For the most part the semicolin is used. After a case, we use a colin. Adding a colin after opening the switch statement, ie: switch($x):, is often a mistake made. There is not colin after that, just a curly bracket.
Let's get into our first example:
$food = "Apple";
echo "I have a banana!";
echo "Orange you glad I didn't say Banana?";
echo "This is the one we want!<br />"; // has an HTML line break at the end
echo "I have an Apple!"; // added a second echo. This will display 2 lines.
echo "I do not have an Apple, Banana, or an Orange";
To sum up a switch statement's functionality, it's the quick way to write a long if elseif elseif elseif elseif elseif elseif elseif else statement.
Create a switch statement on your own.
Declare a variable,
Have at least 3 cases,
And have a default case.
If you have questions, as always just message me.