PHP If...Else...Elseif

This tutorial teaches you how to write decision-making code using if...else...elseif statements in PHP.

 

What is PHP Conditional Statements?

You can use PHP Conditional statements to write code if you want to perform different actions for different conditions. 

While writing programs, there will be situations when you want to execute a particular statement only if some condition is satisfied. In such cases, you use conditional statements.


Conditional Statements in PHP

In PHP, the conditional statements are of four types. These are:

  • if statements
  • if...else statements
  • if...elseif...else statements
  • switch statements (The switch statements will be covered in the next tutorial.)

 

The if statement

If statements are used when you want to execute some code when a condition is true

Syntax:

if(condition) { 

// code to be executed if 'condition' is true 

}

Check the example

<?php

$age = 18;

if($age <= 25)
{
    echo "You are not allowed to ride the bike";
}
?>

Output:

You are not allowed to ride the bike

 

The if...else statement

The if...else statements are used when you want to execute some code when a condition is true and a different code when that condition is false.

Syntax:

if(condition) { 

// code to be executed if 'condition' is true 

} else {

 // code to be executed if 'condition' is false

 }

 

Example

<?php

$age = 19;

if($age <= 18)
{
    echo "You are not allowed to ride the bike";
}
else 
{
    echo "Enjoy the ride";
}
?>

Output:

Enjoy the ride

 

 

The if...else...elseif statement

The if...elseif...else statements are used when you want to execute different code for a different set of conditions and have more than two possible conditions. 

Syntax

if(condition1) { 

// code to be executed if 'condition1' is true 

} elseif(condition2) { 

// code to be executed if 'condition2' is true 

} else { 

/* code to be executed if both 'condition1' and 'condition2' are false */ 

}

 

Example

<?php
// speed in kmph
$speed = 110;

if($speed < 60)
{
    echo "Safe driving speed";
}
elseif($speed > 60 && $speed < 100)
{
    echo "You are burning extra fuel";
}
else 
{
    // when speed is greater than 100
    echo "Its dangerous";
}
?>

Output:

Its dangerous

 

In the example mentioned above, logical operators && have been used. Logical operators are very helpful in writing multiple conditions together.