0
0
PHPprogramming~5 mins

Elseif ladder execution in PHP

Choose your learning style9 modes available
Introduction

An elseif ladder helps you check many conditions one after another. It runs the first true condition and skips the rest.

When you want to choose one action from many options.
When you need to check multiple conditions in order.
When you want to avoid running all checks once one is true.
When you want clear, easy-to-read decision making in your code.
Syntax
PHP
<?php
if (condition1) {
    // code to run if condition1 is true
} elseif (condition2) {
    // code to run if condition2 is true
} elseif (condition3) {
    // code to run if condition3 is true
} else {
    // code to run if none of the above conditions are true
}
?>

The elseif keyword is used between if and else.

Only the first true condition's code runs; others are skipped.

Examples
This checks the score and prints the grade. Since 85 is >= 80 but less than 90, it prints "Grade B".
PHP
<?php
$score = 85;
if ($score >= 90) {
    echo "Grade A";
} elseif ($score >= 80) {
    echo "Grade B";
} else {
    echo "Grade C";
}
?>
This checks the day and prints a message. For Tuesday, it prints "Midweek day" because none of the earlier conditions match.
PHP
<?php
$day = "Tuesday";
if ($day == "Monday") {
    echo "Start of work week";
} elseif ($day == "Friday") {
    echo "End of work week";
} elseif ($day == "Saturday" || $day == "Sunday") {
    echo "Weekend";
} else {
    echo "Midweek day";
}
?>
Sample Program

This program checks the temperature and prints a message about the weather. Since 30 is greater than 25 but not greater than 35, it prints "It's warm today."

PHP
<?php
$temperature = 30;
if ($temperature > 35) {
    echo "It's very hot today.";
} elseif ($temperature > 25) {
    echo "It's warm today.";
} elseif ($temperature > 15) {
    echo "It's cool today.";
} else {
    echo "It's cold today.";
}
?>
OutputSuccess
Important Notes

Remember, only one block runs in an elseif ladder.

Order matters: put the most specific conditions first.

You can have as many elseif parts as you need.

Summary

An elseif ladder checks multiple conditions in order.

It runs the first true condition's code and skips the rest.

Use it to make clear choices between many options.