Tag Archives: else if

Else and else if statements in PHP

In the previous tutorial we looked at if statements in PHP. In this tutorial we will look at how to specify more conditions by using the else and else if statements. If you are testing multiple conditions you can use an if statement along with else if and else statements. You can also place an if statement inside another if statement – this is known as a nested if statement.

The basic structure of if, else if and else statements looks like this:

if(condition){
  // do something
}
else if(another condition){
  // do something else
}
else{
  // do something completely different if the
  // other two conditions are not met
}

The basic structure of a nested if statement looks like this:

if(condition){
  if(another condition){
     //do something
  }
}

Make sure you use the correct brackets for conditions and statements inside if statements, and also make sure that you have matching closing brackets.

Watch the video below to see how to use if, else if, and else statements in PHP and then scroll down to see the sample code.

Sample PHP code:

<?php
 
 $age = 20;
 
 if($age >= 18){
 echo "You are old enough to vote";
 }
 
 else if($age == 17){
 echo "You can vote on your next birthday";
 }
 
 else{
 echo "You are not old enough to vote";
 }
 
?>

PHP Manual references: