Signup/Sign In

PHP if, else and else if Conditional Statements

While writing programs/scripts, there will be scenarios where you would want to execute a particular statement only if some condition is satisfied. In such situations we use Conditional statements.

In PHP, there are 4 different types of Conditional Statements.

  1. if statements
  2. if...else statements
  3. if...elseif...else statements
  4. switch statement

We will cover the switch statements in the next tutorial.


The if statement

When we want to execute some code when a condition is true, then we use if statement.

Syntax:

if(condition)
{
    // code to be executed if 'condition' is true
}

Here is a simple example,

<?php

$age = 20;

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

The if...else statement

When we want to execute some code when a condition is true, and some other code when that condition is false, then we use the if...else pair.

Syntax:

if(condition)
{
    // code to be executed if 'condition' is true
}
else 
{
    // code to be executed if 'condition' is false
}

Here is a simple example,

<?php

$age = 26;

if($age <= 25)
{
    echo "You are not allowed to consume alchohol";
}
else 
{
    echo "Enjoy the drinks";
}
?>

Enjoy the drinks


The if...else...elseif statement

When we want to execute different code for different set of conditions, and we have more than 2 possible conditions, then we use if...elseif...else pair.

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 */
}

Here is a simple 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";
}
?>

Its dangerous

In the example above, we have also used logical operator &&. Logical operators are very useful while writing multiple conditions together.