The PHP Switch Statement

Guest Author - Diane Cipollo

In a previous tutorial we discussed how to use the PHP if statement in your programs to ask questions and make decisions. By using the if statement you can control the flow of your program. Now we will explore the PHP switch statement which also can be used to control the flow of your program.

The PHP if statement evaluates an expression as true or false. This type of question is called a boolean. Is the sky blue - True or false? However, the switch statement evaluates a case result against a switch expression. This is a fancy way of saying that you can test for more then just true or false. You can also test for simple numbers and strings. Here is the basic switch statement.

switch(expression) { case result1: do this break;

case result2: do this break;

default: do this break;}

switch($sky) { case "red": echo "The sky is red"; break;

case "blue": echo "The sky is blue"; break;

default: echo "The sky has fallen"; break;}

As you can see from the example the switch statement is made up of six parts.

case result: The case statement tests the value of the switch expression - $sky - against the result which in the example is red. If there is a match, the program will complete the accompanying code for that case statement. echo "The sky is red";

break;

The break statement ends the execution of the switch statement. If a match is found and the accompanying code (do this) is completed, then the break statement makes the program ignore or skip over the rest of the switch statement. It will go to the end of the switch statement block and perform the first line of code outside of the block.

default:

The default case statement is a special type of case statement. It is optional. If no match is found in the previous case statements and the program makes it all the way to the end, it will encounter the default case statement. This default case statement tells the program what to do if there is no match. But you might not want the program to do anything. If so you can omit the default case statement.