PHP 5 switch Statement

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

You can consider the switch statement as an alternative to several if statements, a control structure with a range of options. For each option, you can define an action. Switch statements are great for choices with many options, because they are easy to overview and modify to reflect changes in your situation.

Example -

Then we get to the actual switch statement. It consists of the switch keyword and then the condition that we want to evaluate. In our case, we use the $answer variable, which will hold a value passed through the query string. Inside the switch statement, we start defining our case's. The first case is a bit special, because instead of looking for a single value, we use the default keyword to define an action that will happen only if none of the other cases matches. In our example, this allows us to output the question that we want to ask and then some links for answering it. We ask the user which version of PHP they are using, and as soon as they click one of the answer links, we will output an answer for them. If no answer is selected, or if an unknown answer is entered through the query string, we simply output the question, since it's our default case.

Each case is built declared by using the case keyword, the value we wish to check for, a colon, the code we wish to execute if we have the right case, and then the break statement to signal that if a case statement matches, we want the switch statement to end.