PHP if else

In this chapter you will learn:

  1. Description for if else statement
  2. Syntax for if else statement
  3. Note for if else statement
  4. Example - PHP if else statement
  5. Example - PHP if else statement ladder

Description

We can providing an alternative choice with the else statement.

Syntax

The PHP if else statement has the following syntax.


if(condition_0){//from j  a va2s. c  o m
...
}else{
...
}

or


if(condition_0){//from j  av  a  2 s  . c  o  m
...
}elseif (condition_1){

}elseif (condition_2){

}else{
...
}

Note

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

Example 1


<?PHP/*j  a va 2s .  co  m*/
$myValue = 23; 

if ( $myValue  >= 10 ) { 
 echo "greater than 10."; 
} else { 
 echo "Less than 10!"; 
}   
?>

The code above generates the following result.

Example 2

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


<?php/*from j a  v a 2 s  .  co  m*/
       
       $Age = 23; 
       if ($Age < 10) {
               print "You're under 10";
       } elseif ($Age < 20) {
               print "You're under 20";
       } elseif ($Age < 30) {
               print "You're under 30";
       } elseif ($Age < 40) {
               print "You're under 40";
       } else {
               print "You're over 40";
       }
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. When to use switch statement
  2. Syntax for PHP switch statement
  3. Note for switch statement
  4. Example - Using PHP switch statement
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require