PHP If...Else...Elseif


Conditional statements in PHP are what make your code think and make decisions. They allow your program to choose different actions depending on whether a condition is true or false.

In real life, you make decisions all the time — “If it’s raining, take an umbrella. Else, wear sunglasses.”
PHP does the same thing in code.

What Are Conditional Statements in PHP?

Conditional statements tell PHP which block of code to execute depending on certain conditions. They are used in almost every real-world PHP project — from login systems to payment gateways.

Imagine you’re creating a student result system:

  • If a student’s marks are above 90, print “Excellent”.

  • Else if above 75, print “Good”.

  • Else, print “Needs Improvement”.

That’s exactly what conditional logic is.

PHP provides several ways to handle conditional execution:

  1. if statement

  2. if...else statement

  3. if...elseif...else statement

  4. Nested if statements

  5. Shorthand (ternary) operator

Let’s understand each in detail with practical examples.

The if Statement

The simplest and most commonly used form.

<?php
$temperature = 32;

if ($temperature > 30) {
    echo "It's a hot day!";
}
?>
  • PHP checks the expression inside parentheses ( ).

  • If the condition is true, the block inside { } executes.

  • If it’s false, PHP skips that block.

So, if $temperature is greater than 30, the message will appear.

You can use the if statement to check numbers, strings, booleans, arrays, or any expression that evaluates to true or false.

The if...else Statement

When you need to handle two possible outcomes, use if...else.

<?php
$age = 17;

if ($age >= 18) {
    echo "You are eligible to vote.";
} else {
    echo "Sorry, you are not eligible yet.";
}
?>

Here:

  • If $age >= 18, the first message executes.

  • Otherwise, the else part runs.

This type of structure is used in form validation, login checks, and permissions.

The if...elseif...else Statement

When there are multiple conditions, elseif is used. PHP checks them from top to bottom and stops when one condition becomes true.

<?php
$marks = 68;

if ($marks >= 90) {
    echo "Grade: A+";
} elseif ($marks >= 75) {
    echo "Grade: A";
} elseif ($marks >= 60) {
    echo "Grade: B";
} elseif ($marks >= 45) {
    echo "Grade: C";
} else {
    echo "Grade: Fail";
}
?>

How it works:

  • PHP first checks $marks >= 90.

  • If not true, it checks the next condition.

  • Once one condition matches, PHP skips the rest.

This structure is very common in grading systems, tax calculations, and pricing logic.

Nested if Statements

Sometimes, you need to check one condition inside another. That’s called nesting.

<?php
$loggedIn = true;
$isAdmin = false;

if ($loggedIn) {
    if ($isAdmin) {
        echo "Welcome Admin!";
    } else {
        echo "Welcome User!";
    }
} else {
    echo "Please log in first.";
}
?>

Here:

  • The outer if checks if the user is logged in.

  • Inside it, another if checks if the user is an admin.

Nested if statements help when multiple levels of conditions are involved, like checking user roles, permissions, or account status.

However, avoid nesting too deeply. It can make the code hard to read. If logic becomes complex, use logical operators instead.

Combining Conditions with Logical Operators

You can combine multiple conditions using logical operators like &&, ||, and !.

<?php
$age = 20;
$hasID = true;

if ($age >= 18 && $hasID) {
    echo "Entry allowed.";
} else {
    echo "Entry denied.";
}
?>

Explanation:

  • && means AND (both conditions must be true).

  • || means OR (any one condition must be true).

  • ! means NOT (reverses the result).

Example:

<?php
$isWeekend = false;
$isHoliday = true;

if ($isWeekend || $isHoliday) {
    echo "You can relax today!";
} else {
    echo "It's a work day!";
}
?>

These logical combinations make your conditions more flexible and readable.

Using the Shorthand If (Ternary Operator)

When you want a quick one-line condition, use the ternary operator.

<?php
$age = 18;
echo ($age >= 18) ? "Eligible to vote" : "Not eligible yet";
?>

Here:

  • If $age >= 18 is true, it prints “Eligible to vote”.

  • Otherwise, “Not eligible yet”.

This is best for short, simple conditions — for example, displaying messages or formatting data inline.

Checking String and Array Conditions

PHP’s if statement can check more than numbers. You can check if a string is empty, or if an array has elements.

<?php
$username = "Vicky";

if (!empty($username)) {
    echo "Welcome, $username!";
} else {
    echo "Please enter your username.";
}

$students = ["Vicky", "Sanjana", "Vrinda"];
if (count($students) > 2) {
    echo "There are more than two students in the list.";
}
?>

Functions like empty(), isset(), and count() are often used with conditions to validate data.

Nested Conditions vs Combined Conditions

Let’s say you want to check two things: if a student passed and if they scored distinction.

Instead of nesting:

if ($marks >= 40) {
    if ($marks >= 75) {
        echo "Passed with distinction";
    } else {
        echo "Passed";
    }
}

You can combine conditions:

if ($marks >= 75) {
    echo "Passed with distinction";
} elseif ($marks >= 40) {
    echo "Passed";
} else {
    echo "Failed";
}

Combined conditions are cleaner, easier to read, and perform slightly better.

Real-World Example: Discount Calculator

Here’s how if...elseif...else might appear in a real web application:

<?php
$purchase = 2500;

if ($purchase >= 5000) {
    echo "You get a 25% discount!";
} elseif ($purchase >= 2000) {
    echo "You get a 15% discount!";
} elseif ($purchase >= 1000) {
    echo "You get a 10% discount!";
} else {
    echo "No discount available.";
}
?>

Such logic is often used in e-commerce websites for promotions, coupon systems, and loyalty rewards.

Common Mistakes to Avoid

  1. Using = instead of ==:
    = assigns a value; == compares values.

    if ($x = 10) { } // Wrong (assigns 10)
    if ($x == 10) { } // Correct
    
  2. Missing Curly Braces {}:
    Always use braces for clarity, even for one-line conditions.

  3. Writing Unreachable Code:
    If one condition already covers a range, don’t repeat it below.

  4. Over-Nesting Conditions:
    Use logical operators or switch statements when conditions pile up.

Best Practices

  • Keep each condition focused and readable.

  • Combine logical operators to reduce nesting.

  • Use elseif for mutually exclusive checks.

  • Prefer strict comparison (===) when checking type-sensitive data.

  • Add comments for complex conditions.

  • Don’t overuse ternary operators; they can reduce clarity.

Summary of the Tutorial

  • PHP conditional statements decide what code runs based on a condition.

  • if handles one check, if...else adds an alternative, and if...elseif...else handles multiple outcomes.

  • Use logical operators for combining conditions.

  • Use the ternary operator for short expressions.

  • Check strings and arrays with functions like empty(), isset(), and count().

  • Write clean, readable, and well-structured conditions to make your PHP code more maintainable.

In short, mastering if...else...elseif logic is key to writing dynamic, intelligent PHP applications.


Practice Questions

  1. Write a PHP program to check if a number is positive, negative, or zero.

  2. Create a PHP script that checks whether a person is eligible to vote based on their age.

  3. Write a PHP code that prints “Pass” if marks are greater than or equal to 40, otherwise print “Fail.”

  4. Create a PHP program to determine the largest of three numbers using if...elseif...else.

  5. Write a PHP script to display “Good Morning”, “Good Afternoon”, or “Good Evening” based on the current time.

  6. Create a PHP program that checks if a year is a leap year or not.

  7. Write a PHP code to check whether a given character is a vowel or consonant.

  8. Create a PHP script to determine if a number is even or odd.

  9. Write a PHP program that checks if a user is logged in and whether they are an admin or normal user.

  10. Create a PHP code to calculate the grade of a student based on marks using if...elseif...else conditions.


Go Back Top