Using else Statements


Using else Statements

The if statement has more power built into it. You know that if the if statement's condition is true, the if statement's internal statement will be executed. But what if the if statement's condition is false? Does that mean you can't execute any code?

Nope. You can use an else statement (also called an else clause) to execute code when an if statement's condition is false. For example, take a look at this code; the if statement's condition is false, so the internal statement echo "We're in the comfort zone."; will not be executed:

 <?php     $temperature = 26;     if ($temperature > 75 && $temperature < 80) {         echo "We're in the comfort zone.";     }     else {         echo "We're outside the comfort zone.";     } ?> 

Because the if statement's condition is false, however, the internal statement in the else statement will be executed. In this case, that means you'll see this from the script:

 We're outside the comfort zone. 

Now you can handle if statements either waywhether the if statement's condition is true or false.

Here's another example; in this case, we'll check a student's grade on a test:

 <?php     $score = 89;     if ($score > 50) {         echo "Whew, you passed.";     }     else {         echo "Uh oh.";     } ?> 

The results:

 Whew, you passed. 



    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