PHP - If-Else Statements


Advertisements

Previous Page Next Page

If Statement:

The If statement is used to execute a block of code when the condition is evaluated to be true. When the condition is evaluated to be false, the program will skip the if-code block.

Syntax


if(condition){
  statements;
}

Flow Diagram:

PHP If Loop

<?php
    $i = 15;
    if ( $i % 3 == 0){
        echo $i." is divisible by 3.\n"; 
    }
?>

Output

15 is divisible by 3.

If-else Statement:

The else statement is always used with If statement. It is used to execute block of codes whenever If condition gives false result.

Syntax


if(condition){
  statements;
}
else{
  statements;
}

Flow Diagram:

PHP If-else Loop

<?php
    $i = 16;
    if ( $i % 3 == 0){
        echo $i." is divisible by 3.\n"; 
    }
    else{
        echo $i." is not divisible by 3.\n"; 
  }
?>

Output

16 is not divisible by 3.

elseif Statement:

elseif statement is used to tackle multiple conditions at a time. For adding more conditions, elseif statement in used. Please see the syntax.

Syntax


if(condition){
  statements;
}
elseif(condition){
  statements;
}
...
...
...
else {
  statements;
}
}

Flow Diagram:

PHP If-elseif-else Loop

<?php
    $i = 16;
    if ( $i > 25){
        echo $i." is greater than 25.\n"; 
    }
    elseif($i <=25 && $i >=10){
        echo $i." lies between 10 and 25.\n"; 
    }
    else{
        echo $i." is less than 10.\n"; 
  }
?>

Output

16 lies between 10 and 25.

Previous Page Next Page
Advertisements