PHP - if else statement

Introduction

Providing an Alternative Choice with the else Statement

You can add an else statement to an if construction.

This lets you run one block of code if an expression is true , and a different block of code if the expression is false.

For example:

Demo

<?php

        if ( $widgets  >= 10 ) {
           echo "more then 10.";
        } else {//from   w ww .j  a  va2s  . c  om
           echo "Less than 10 left.";
        }
?>

Result

If $widgets is greater than or equal to 10, the first code block is run.

If $widgets is less than 10, the second code block is run.

You can even combine the else statement with another if statement to make as many alternative choices as you like:

Demo

<?php

         if ( $widgets  >= 10 ) {
           echo "plenty.";
         } else if ( $widgets  >= 5 ) {
           echo "Less than 10 left.!";
         } else {
           echo "Less than 5 left!";
         }/*from w  w w  . j av  a 2  s.  co  m*/
?>

Result

If there are 10 or more widgets, the first code block is run.

If $widgets is less than 10, control passes to the first else statement, which in turn runs the second if statement: if ( $widgets >= 5 ).

PHP gives you a special statement - elseif - that you can use to combine an else and an if statement.

So the preceding example can be rewritten as follows:

Demo

<?php

         if ( $widgets  >= 10 ) {
           echo "plenty of widgets.";
         } elseif ( $widgets  >= 5 ) {
           echo "Less than 10 widgets left.";
         } else {
           echo "Less than 5 widgets left! Order more now!";
         }//ww w  . ja v  a 2 s  .  c o m

?>

Result

Related Topic