Trusted answers to developer questions

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

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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
Did you find this helpful?