Using Switch Statements


You create a switch statement with the keyword switch, and 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 such 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 what the switch statement looks like:

 switch (expression){   case data:     statement     break;   case data:     statement     break;   case data:     statement     break;   [default:     statement]   }

Note 

If the value of expression doesn’t match any data item, the code in the optional default statement will be executed.

In this example, different text based on the temperature, switch.php, is displayed:

 <html>    <head>        <title>            Using the switch statement        </title>    </head>    <body>        <h1>            Using the switch statement        </h1>        <?          $temperature = 75;          switch ($temperature){            case 75:              echo "Nice weather.";              break;            case 76:              echo "Still nice weather.";              break;            case 77:              echo "Getting warmer.";              break;              default:                echo "Temperature outside the range.";              }        ?>     </body> </html>

You can see switch.php at work in Figure 12.12, which shows that it’s nice weather.

image from book
Figure 12.12: Using switch statements



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

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