The switch Statement


The switch Statement

 switch ($expr) {     case test1:         statement1         break;     case test2:         statement2         break;     case test3:         statement3         break;     default:         statement4     } 

The switch statement is much like a series of successive if statements using the same expression. The idea is to compare the same expression with many different test values, executing different code depending on which test value it matches.

For example, here's how you might test the value in $expr using a ladder of if and elseif statements:

 <?php     if ($expr == 1) {         echo "Expr is 1";     } elseif ($expr == 1) {         echo "Expr is 2";     } elseif ($expr == 3) {         echo "Expr is 3";     } ?> 

And here's how this would look as a switch statement:

 switch ($expr) { case 1:     echo "Expr is 1";     break; case 2:     echo "Expr is 2";     break; case 3:     echo "Expr is 3";     break; } 

When a case statement is found with a value that matches the value of the switch expression, PHP continues to execute the statements until the end of the switch block, or until it encounters a break statement. If you don't write a break statement at the end of a case statement, PHP will go on executing the statements of the following case(s). For example, take a look at this switch statement:

 switch ($expr) { case 1:     echo "Expr is 1"; case 2:     echo "Expr is 2"; case 3:     echo "Expr is 3"; } 

If $expr is 1, PHP will execute all of the echo statements.

You can also use the default keyword, which will match anything that wasn't matched by the other cases. If you use it, the default statement should be the last case statement because no case statement after it will be executed. Here's an example:

 switch ($expr) { case 1:     echo "Expr is 1"; case 2:     echo "Expr is 2"; case 3:     echo "Expr is 3"; default:     echo "Sorry, expr didn't match 1, 2, or 3."; } 

This switch statement works just as this if statement does:

 <?php     if ($expr == 1) {         echo "Expr is 1";     } elseif ($expr == 1) {         echo "Expr is 2";     } elseif ($expr == 3) {         echo "Expr is 3";     } else {         echo "Sorry, expr didn't match 1, 2, or 3.";     } ?> 



    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