php

PHP Decision Makings


If else conditions are written where the logic is straightforward. There are various ways to use if statement in PHP.

  • If
  • If-else
  • If-else-if
  • Nested if

 

PHP If Statement

PHP if is used to execute a block of code based on the condition, only if the condition is true.

 

Syntax:

<?php
    if($condition){
        // Code Starts here
    }
?>

 

Example:

<?php
    $no = 7;
    if($no > 5)
    {
        echo "$no is greater than 5";
    }
?>

 

Output:

 

PHP If-else Statement:

The If-else statement allows to execute different blocks of code based on whether a specified condition is true or false. It is also known as control-flow statements.

 

Syntax:

<?php
    if($codition)
    {
        // Code to be executed if codition is TRUE
    }
    else
    {
        // Code to be executed if condition is FALSE
    }
?>

 

Example:

<?php
    $no = 6;
    if($no > 10)
    {
        echo "$no is greater than 10";
    }
    else{
        echo "$no is lesser than 10";
    }
?>

 

Output:

 

PHP If-else-if Statement

The If-else-if statement is used to check more than two conditions. So, we can check multiple conditions using this statement.

 

Syntax: 

<?php
    if($condition1)
    {
        // Code to be executed if condition1 is TRUE
    }
    else if($condition2)
    {
        // Code to be executed if condition2 is TRUE
    }
    else if($condition3)
    {
        // Code to be executed if condition3 is TRUE
    }
    else
    {
        // Code to be executed if all conditions are FALSE
    }
?>

 

Example:

<?php
    $no = 60;
    if($no < 10)
    {
        echo "$no is greater than 10";
    }
    elseif($no < 25)
    {
        echo "$no is lesser than 10";
    }
    elseif($no < 45)
    {
        echo "$no is lesser than 10";
    }
    else
    {
        echo "All conditions are FALSE";
    }
?>

 

Output:

 

Nested if statement:

A nested if statement is an if statement that is the target of another if statement.

 

Syntax: 

<?php
    if($condition1){
        // Code to be executed if condition1 is correct
        if($condition2){
            // Code to be executed if codition1 & condition2 are correct
        }
    }
?>

 

Example:

<?php
    $no = 16;
    if($no > 10)
    {
        echo "$no is greater than 10";
        if($no > 20)
        {
            echo "but $no is not greater than 20";
        }
    }
?>

 

Output: