Using switch Statements


Using switch Statements

If you have many conditions to test, even using elseif statements can become a little tedious. For those circumstances when you have plenty of conditions to check, you should consider a switch statement, which is built for testing multiple conditions.

A switch statement starts with the keyword switch; you indicate the item you're testing by placing it in parentheses. You create multiple tests using the case statement, specifying a value for each statement. If the switch's test value matches a case statement's value, the internal statements in the case statement are executed up to a break statement, which ends the case statement. If no case matches, the statements in a default statement, if present, are executed. Here's an example, which displays different text based on the temperature:

 <?php $temperature = 70; switch ($temperature){     case 70:         echo "Nice weather.";         break;     case 71:         echo "Still nice weather.";         break;     case 72:         echo "Getting warmer.";         break;     default:         echo "Temperature outside the range."; } ?> 

In this case, you'd see:

 Nice weather. 

Pretty cool. Note that the values you specify in a case statement may only be integer or floating point numbers and strings.

What if you want to match multiple values in the same case statement? In that case, you can omit the break statement in various case statements, which means that execution will fall through to the next case statement. For example, to match temperature ranges such as 70-72, 73-75, and so on, take a look at phpswitch.php, Example 2-6.

Example 2-6. Using the switch statement, phpswitch.php
 <HTML>     <HEAD>         <TITLE>             Using the switch statement         </TITLE>     </HEAD>     <BODY>         <H1>             Using the switch statement         </H1>         <?php             $temperature = 74;             switch ($temperature) {                 case 70:                 case 71:                 case 72:                     echo "Nice weather.";                     break;                 case 73:                 case 74:                 case 75:                     echo "Still nice weather.";                     break;                 case 76:                 case 77:                 case 78:                     echo "Getting warmer.";                     break;                 default:                     echo "Temperature outside the range.";             }         ?>     </BODY> </HTML> 

The results appear in Figure 2-7.

Figure 2-7. Using the switch statement.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net