ElseIf in PHP: A Comprehensive Guide

As the name suggests, the elseif statement is a combination of the else and if statements in PHP. This statement allows you to check multiple conditions and execute specific blocks of code based on those conditions.

You can add multiple elseif statements within a single if-else control structure to handle different scenarios. An elseif statement will execute only when the previous if condition evaluates to false.

The if-elseif-else statement is a multiway decision structure in PHP that is particularly useful when you need to test several conditions sequentially. As soon as one condition evaluates to true, the corresponding block of code is executed. If none of the conditions are met, an optional else block executes the default case.

It’s important to note that you can also write the elseif statement as else if (with a space). The output in both the cases will be same.

Syntax of ElseIf Statement in PHP


Here is the general syntax of the if-elseif-else statement in PHP:

if (condition1) {
    // This block of code executes if condition1 is true.
} elseif (condition2) {
   // This block of code executes if condition1 is false and condition2 is true.
} elseif (condition3) {
   // This block of code executes if condition1 and condition2 are false, and condition3 is true.
} else {
   // This block of code executes if none of the above conditions are true.
}

In the syntax of the if-elseif-else statement:

  • You can use multiple elseif statements within a single if-else control structure to evaluate multiple conditions.
  • The else block is optional but serves as a useful fallback to handle cases where none of the specified conditions are true.
  • The test conditions are evaluated sequentially from top to bottom. Execution stops as soon as a condition evaluates to true.


Key Points:

  • The if statement evaluates the first condition (condition1). If it is true, its code block is executed, and the rest of the structure is ignored.
  • The elseif statements evaluate subsequent conditions (condition2, condition3, etc.) only if all preceding conditions are false.
  • The optional else block executes if none of the if or elseif conditions evaluate to true.

Flowchart Diagram of If ElseIf Else Statement in PHP


The flowchart diagram for PHP if-elseif-else has shown in the below figure.

PHP elseif statement flowchart diagram

Let’s understand how the elseif statement works with the if-else statement in PHP using a flowchart diagram.


The if-elseif-else statement works in the following steps:

(1) If the first specified condition (condition1) evaluates to true, the code block inside the if statement will execute, and the rest of the elseif statements will be skipped.

(2) If the condition1 is false and the elseif condition (condition2) evaluates to true, the code block associated with that elseif will execute, and the remaining elseif conditions will be bypassed.

(3) If both condition1 and condition2 are false, the next elseif condition (condition3) is evaluated. If it evaluates to true, its corresponding code block will execute, and the rest will be ignored.

(4) If all the above conditions are false, the final else block (if present) associated with the top if statement will execute.

(5) The statement inside the else block acts as a default case. If all previous conditions fail, the code block associated with the else will execute. If there is no else block and none of the conditions are true, no action will take place.

Basic Examples of ElseIf in PHP


Example 1:

<?php
$num = 20;
if ($num > 0) {
     echo "Number is positive.";
} elseif ($num < 0){
     echo "Number is negative.";
} else {
     echo "Number is zero.";
}
?>
Output:
      Number is positive.


Example 2:

<?php
$age = 25;

if ($age < 18) {
    echo "You are a minor.";
} elseif ($age >= 18 && $age <= 30) {
    echo "You are a young adult.";
} elseif ($age > 30 && $age <= 50) {
    echo "You are in your prime.";
} else {
    echo "You are enjoying the golden years.";
}
?>
Output:
      You are a young adult.

Let’s take a simple example in which we will add marks of 3 subjects and calculate percentage and grade according to percentage using PHP if-elseif-else statement.

Example 3:

<?php
$eng = 85;
$science = 82;
$maths = 95;

$total = $eng + $science + $maths;
$per = $total/3;
echo "Total marks: " . $total. "\n";
echo "Percentage: " . $per . "\n";

if ($per >= 90.0) {
     echo "Grade A";
} elseif ($per >= 80.0) {
     echo "Grade B";
} elseif ($per >= 70.0) {
     echo "Grade C";
} elseif ($per >= 60.0) {
     echo "Grade D";
} else {
     echo "Grade F";
}
?>
Output:
      Total marks: 262
      Percentage: 87.333333333333
      Grade B

In this example code, PHP evaluates the conditions sequentially. Since $per is 87.33, the second condition $per >= 80.0 evaluates to true, and “Grade: B” is displayed. The rest of the else if statements will skip.

Example 4:

<?php
$temp = 20;
if ($temp > 25) {
    echo "It's a hot day!";
} elseif ($temp < 5){
    echo "It's a cold day!";
} else {
    echo "The weather is moderate.";
}
?>
Output:
      The weather is moderate.

In this example, “The weather is moderate.” will display on the console or browser because the temperature is neither greater nor less than 5.

Best Practices for Using ElseIf


There are some key points while using elseif statement inside if-else statement in PHP which you should keep in mind.

  • Avoid creating overly complex conditions.
  • Avoid to use too many elseif blocks. If you have many specific conditions to check, consider using a switch statement instead of multiple elseif blocks for better clarity and performance.
  • Always use an else block to handle unexpected inputs or define a default case.
  • Always include curly braces for each block of code, even if it contains only a single statement.
  • Omitting curly braces can lead to logical errors and make your code harder to debug.

Quiz and Exercise


1. Quiz Question: What will be the output of the following code?

<?php
$marks = 65;
if ($marks >= 75) {
    echo "Distinction";
} elseif ($marks >= 60) {
    echo "First Class";
} elseif ($marks >= 50) {
    echo "Second Class";
} else {
    echo "Fail";
}
?>

Options:

  • a) Distinction
  • b) First Class
  • c) Second Class
  • d) Fail

Answer: b) First Class

2. Exercise:

Write a PHP script using elseif to categorize a person based on their BMI value.

BMI ValueCategory
Less than 18.5Underweight
18.5 to 24.9Normal weight
25.0 to 29.9Overweight
30.0 or greaterObesity

 

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the founder of Scientech Easy and a passionate coding educator with 8 years of professional experience in Java, Python, web development, and core computer science subjects. With expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He consistently publishes in-depth tutorials, practical coding examples, and valuable learning resources for beginners as well as working professionals. Each article is carefully researched and reviewed to ensure accuracy, quality, and real-world relevance.