Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
if-else
if-elseif
if family
communitycreator

How to use the if-else and if-elseif statements in PHP

Saad Akbar

We use conditional statements in programming to apply different actions on different conditions. if, if-else, if-elseif-else statements are conditional statements in PHP.

The if statement syntax

if (specific condition) {
  execute code if the condition is true;
}

Example

The if condition checks if the age is greater than 60. If this condition is true, it prints Retired.

<?php
    $age = 61;

    if($age > 60){
        echo 'Retired'; // Display Retired if age is greater than 60
    } 
?>

The if-else statement syntax

if (specific condition) {
  execute code if the condition is true;
}else{
  execute code if the condition is false;
}

Example

The if condition checks if the age is greater than 60 or not. If the condition is true, then it will print Retired. Otherwise, Not Retired will be printed.

<?php
$age = 40;

if($age > 60){
    echo 'Retired'; // Display Retired if age is greater than 60
} else{
    echo 'Not Retired'; // Display Not Retired if age is less than 60
}
?>

The if-elseif-else statement syntax

if (specific condition) {
  execute code if the condition is true;
}
elseif(condition){
  execute code if the previous condition is false
   and this condition is true;
}
else{
  execute code if the above conditions are false;
}

Example

The if condition checks if the age is greater than 60 or not. If the condition is true, it will print Retired. Otherwise, if the age is greater than 40 and not greater than 60, Senior Employee is printed. Lastly, if the first two conditions are false, Junior Employee will be printed.

<?php
    $age = 40;

    if($age > 60){
        echo 'Retired'; // Display Retired if age is greater than 60
    } elseif($age > 40){
        echo 'Senior Employee'; // Display Senior Employee if age is greater than 40
    }
    else{
        echo 'Junior Employee'; 
    }

?>

RELATED TAGS

php
if-else
if-elseif
if family
communitycreator
RELATED COURSES

View all Courses

Keep Exploring