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  w w . ja  v  a2s . co  m
           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!";
         }//w w w .j a v  a  2s  .  c om
?>

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!";
         }/*from ww w .  ja v  a 2s  . c  om*/

?>

Result

Related Topic