php if else and elseif

Part of the course: php for beginners

php if else and elseif

1. Introduction to Conditional Statements in php

1.1 What Are Conditional Statements?

Conditional statements are programming structures that allow your code to make decisions. They check whether a certain condition (or set of conditions) is true or false, and based on that result, the program chooses what action to perform next.
In PHP, the most commonly used conditional statements are if, else, and elseif. These statements help your script behave differently depending on different situations—for example, checking if a user is logged in, verifying passwords, comparing numbers, or making decisions based on user input.

1.2 Why Use Conditions in Programming?

Conditions are essential in programming because they enable dynamic and flexible behavior. Without conditional statements, a program would only run in a straight line, doing the same thing every time.
By using conditions, you can:

  • Control the flow of your code

  • Perform different actions based on different inputs

  • Validate user data or system states

  • Build interactive and smart applications

  • Make decisions based on logic (e.g., “if this happens, do that”)

In short, conditions allow your PHP applications to think, react, and respond—making them much more powerful and useful.

2. Understanding the if Statement

2.1 Syntax of if

The if statement is the simplest and most commonly used conditional structure in PHP.
Its purpose is to run a block of code only when a specific condition is true.

The basic syntax is:

if (condition) {
// Code to execute if the condition is true
}
  • The condition must return either true or false.

  • If the condition is true, the code inside the braces {} runs.

  • If the condition is false, PHP skips that block and moves on.

2.2 How Conditions Are Evaluated

PHP evaluates conditions by checking whether the expression inside the parentheses is truthy or falsy.

Examples of expressions considered true:

  • 5 > 2

  • $age == 18

  • !empty($name)

Examples of expressions considered false:

  • 0

  • "" (empty string)

  • null

  • false

  • 3 < 1

PHP uses comparison operators (like ==, ===, >, <, !=) and logical operators (&&, ||, !) to determine the result of the condition.

2.3 Basic Examples of if

Example 1: Simple number comparison

$number = 10;

if ($number > 5) {
echo “The number is greater than 5.”;
}

Output:
The number is greater than 5.

Example 2: Checking a variable

$username = "Ali";

if ($username == “Ali”) {
echo “Welcome, Ali!”;
}

Example 3: Condition based on a function

if (is_numeric("123")) {
echo "This is a number.";
}

3. Working with the else Statement

3.1 Syntax of else

The else statement is used when you want to execute a block of code only if the if condition is false.
It does not have its own condition—it’s simply the alternative to if.

Basic syntax:

if (condition) {
// Code runs if the condition is true
} else {
// Code runs if the condition is false
}
  • The else block is optional, but when used, it must directly follow an if or elseif.

  • There can only be one else in a conditional chain.

3.2 When to Use else

You use else when you want your program to do something in all cases where the main condition is not true.

Use else when:

  • You need a fallback action

  • You want to handle the opposite outcome of the main condition

  • You want to ensure that at least one block of code executes

Examples of common uses:

  • If a username is correct → allow login
    Else → show an error message

  • If a number is positive
    Else → treat it as non-positive

  • If a form field has data
    Else → show a required-field warning

else guarantees your code always has a response when the if condition fails.

3.3 Example: Using if with else

Example 1: Checking age

$age = 15;

if ($age >= 18) {
echo “You are an adult.”;
} else {
echo “You are not an adult.”;
}

Output:
You are not an adult.

Example 2: Login check

$username = "Sara";

if ($username == “Sara”) {
echo “Login successful.”;
} else {
echo “Login failed.”;
}

Example 3: Even or odd number

$number = 7;

if ($number % 2 == 0) {
echo “The number is even.”;
} else {
echo “The number is odd.”;
}

4. Using the elseif Statement

4.1 Syntax of elseif

The elseif statement is used when you want to check multiple conditions, one after another.
If the first if condition is false, PHP will move on and evaluate the elseif condition.

Basic syntax:

if (condition1) {
// Runs if condition1 is true
} elseif (condition2) {
// Runs if condition1 is false and condition2 is true
} else {
// Runs if none of the above conditions are true
}

Notes:

  • You can have as many elseif statements as needed.

  • It must come between if and else.

  • Only the first true condition will run; the rest will be ignored.

4.2 Difference Between else and elseif

  • elseif:

    • Checks a new condition.

    • Used when there are multiple possible outcomes.

  • else:

    • Has no condition.

    • Runs only if all previous conditions are false.

    • Always appears last in the chain.

Example difference:

if ($score > 90) {
// first condition
} elseif ($score > 75) {
// second condition (new condition)
} else {
// fallback (no condition)
}

4.3 Multiple Conditions with elseif

You use multiple elseif statements when you want to test several scenarios in order.

Example situations:

  • Grading systems

  • Choosing between several categories

  • Price or discount ranges

  • Age groups

  • Checking input types

Flow:

  1. PHP checks the first condition.

  2. If false, it checks the second condition.

  3. If false again, it continues to the next elseif.

  4. If none match, the else statement runs (if present).

This structure makes your code organized, readable, and logical.

4.4 Practical Examples

Example 1: Grading system

$score = 82;

if ($score >= 90) {
echo “Grade: A”;
} elseif ($score >= 80) {
echo “Grade: B”;
} elseif ($score >= 70) {
echo “Grade: C”;
} else {
echo “Grade: D”;
}

Example 2: Age category

$age = 25;

if ($age < 13) {
echo “Child”;
} elseif ($age < 20) {
echo “Teenager”;
} elseif ($age < 60) {
echo “Adult”;
} else {
echo “Senior”;
}

Example 3: Temperature status

$temp = 30;

if ($temp < 0) {
echo “Freezing”;
} elseif ($temp < 20) {
echo “Cold”;
} elseif ($temp < 30) {
echo “Warm”;
} else {
echo “Hot”;
}

5. Combining if, elseif, and else

5.1 Full Conditional Flow

Combining if, elseif, and else allows you to create a complete decision-making structure that handles multiple scenarios in a clean and organized way.

The flow works like this:

  1. PHP checks the if condition first.

    • If it’s true, the code inside it runs and the rest is ignored.

  2. If the if condition is false, PHP checks the first elseif condition.

    • If true, that block runs and execution stops.

  3. PHP continues checking any additional elseif conditions, one by one.

    • The first one that evaluates to true will run.

  4. If none of the conditions are true, the final else block runs (if you include one).

This ensures your program always selects the first matching condition and skips the rest, preventing unnecessary processing.

Example of a full flow:

$hour = 14;

if ($hour < 12) {
echo “Good morning!”;
} elseif ($hour < 18) {
echo “Good afternoon!”;
} else {
echo “Good evening!”;
}

Output:
Good afternoon!

5.2 Best Practices for Readable Code

Writing clear and readable conditional statements is important for maintaining your code. Here are the best practices:

1. Use Clear and Simple Conditions

Avoid overly complex expressions.
Good:

if ($age >= 18)

Bad:

if (($age >= 18 && $status == "active") || ($age > 17 && !empty($status)))

If conditions become complicated, break them into variables or functions.

2. Keep Indentation Clean

Always indent code inside if, elseif, and else blocks.
This makes the logic much easier to follow:

if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B";
} else {
echo "C";
}

3. Use elseif Instead of Nested if When Possible

Bad (nested if):

if ($score >= 60) {
if ($score >= 80) {
echo "Great";
}
}

Better (with elseif):

if ($score >= 80) {
echo "Great";
} elseif ($score >= 60) {
echo "Pass";
}

4. Put the Most Common or Most Important Condition First

This can make your code more efficient.

Example:

if ($userLoggedIn) {
// Most common case first
} elseif ($guestMode) {
// Less common
} else {
// Rare case
}

5. Always Use else for a Safe Fallback (When Appropriate)

Use else to catch unexpected values or errors:

if ($mode == "easy") {
echo "Easy mode";
} elseif ($mode == "hard") {
echo "Hard mode";
} else {
echo "Unknown mode";
}

6. Common Mistakes and How to Avoid Them

When using if, elseif, and else in PHP, beginners often run into simple but important mistakes. Understanding these common errors will help you write cleaner, safer, and more reliable code.

6.1 Missing Braces

In PHP, you can write an if statement without braces if there is only one line of code inside it:

if ($x > 10)
echo "Greater than 10";

However, this often leads to mistakes — especially when adding more lines later. Without braces, it becomes easy to confuse which lines belong to which condition.

Problem Example:

if ($x > 10)
echo "Greater";
echo "Number";

Many beginners expect both lines to run only if the condition is true, but the second line will run no matter what, because it is not inside braces.

Correct Version (using braces):

if ($x > 10) {
echo "Greater";
echo "Number";
}

Best Practice:
Always use braces { } — even for one-line conditions. It prevents bugs and makes code easier to read.

6.2 Incorrect Comparison Operators

Many mistakes come from using the wrong comparison operator or misunderstanding their differences.

Common comparison operators:

  • == → equal (values only)

  • === → identical (values + data type)

  • != → not equal

  • !== → not identical

  • > → greater than

  • < → less than

  • >= → greater or equal

  • <= → less or equal

Problem Example:

if ("5" === 5) {
echo "Match";
}

This returns false because the types are different (string vs integer).

Fix:

if ("5" == 5) {
echo "Match";
}

Or, convert types:

if ((int)"5" === 5) {
echo "Match";
}

Tip:
Use === when you care about type safety.
Use == only when type does not matter.

6.3 Using = Instead of ==

This is one of the most common mistakes in PHP and almost always leads to bugs.

  • = is the assignment operator

  • == is the comparison operator

Beginners often accidentally write:

if ($x = 5) {
echo "Equal";
}

What actually happens:

  • $x = 5 assigns the value 5 to $x

  • The expression returns true because the assigned value (5) is considered true

This means the block always runs, even when unintended.

Correct Version:

if ($x == 5) {
echo "Equal";
}

Even better, to avoid accidental assignments:

if (5 == $x) { // “Yoda condition”
echo "Equal";
}

If you accidentally write 5 = $x, PHP will throw an error, protecting you from mistakes.

7. Advanced Usage Examples

The more you work with PHP, the more you’ll find situations where simple conditions are not enough. In these cases, you can use advanced techniques like nested conditions, logical operators, and real-world conditional logic to build smarter and more flexible applications.

7.1 Nested if Statements

A nested if is an if statement placed inside another if or elseif block.
This is useful when you want to check a second condition, but only if the first one is true.

Example: Access control (nested conditions)

$loggedIn = true;
$userRole = "admin";

if ($loggedIn) {
if ($userRole == “admin”) {
echo “Welcome, Admin!”;
} else {
echo “Access denied: Not an admin.”;
}
} else {
echo “Please log in first.”;
}

Explanation:

  • First, PHP checks if the user is logged in.

  • Only if that is true, it checks the second condition (user role).

When to use:

  • Multi-step validation

  • Checking multiple requirements in order

  • Advanced permission systems

Best Practice:
Avoid deep nesting—too many nested ifs make the code hard to read.
If possible, use elseif or logical operators instead.

7.2 Complex Logical Conditions (&&, ||)

Logical operators let you combine multiple conditions inside a single if statement.

Common logical operators:

  • && → AND
    All conditions must be true.

  • || → OR
    At least one condition must be true.

  • ! → NOT
    Reverses a condition’s result.

Example 1: AND (&&)

$age = 25;
$hasTicket = true;

if ($age >= 18 && $hasTicket) {
echo “You may enter the event.”;
}

Both conditions must be true for the message to display.

Example 2: OR (||)

$temperature = 35;

if ($temperature > 30 || $temperature < 0) {
echo “Extreme temperature warning!”;
}

The message displays if either condition is true.

Example 3: NOT (!)

$isOnline = false;

if (!$isOnline) {
echo “User is not online.”;
}

!$isOnline becomes true because $isOnline is false.

Combining Logical Operators

You can combine multiple logical expressions:

$age = 22;
$member = true;
$hasCoupon = false;

if (($age > 18 && $member) || $hasCoupon) {
echo “Discount applied!”;
}

This means:

  • If the user is over 18 AND a member, OR

  • If they have a coupon
    → they receive a discount.

Use parentheses () to keep conditions organized and clear.

7.3 Real-World Application Example

Example: Login system with multiple conditions

$username = "Ali";
$password = "1234";
$isBlocked = false;

if (!$isBlocked) {
if ($username == “Ali” && $password == “1234”) {
echo “Login successful!”;
} elseif ($username == “Ali”) {
echo “Incorrect password.”;
} else {
echo “User not found.”;
}
} else {
echo “Your account is blocked. Contact support.”;
}

Explanation:

  • First, check if the account is blocked.

  • Then check username + password.

  • If the username is correct but the password is wrong, show a specific message.

  • If neither matches, show user-not-found.

Example: Product price + discount logic

$price = 120;
$isMember = true;
$hasCoupon = false;

if ($price > 100) {
if ($isMember || $hasCoupon) {
echo “You get a discount!”;
} else {
echo “No discount available.”;
}
} else {
echo “Price too low for discount.”;
}

Example: Weather conditions

$rain = true;
$wind = false;

if ($rain && $wind) {
echo “Severe weather alert!”;
} elseif ($rain) {
echo “It’s raining. Take an umbrella.”;
} elseif ($wind) {
echo “It’s windy outside.”;
} else {
echo “Weather is clear.”;
}

8. Conclusion

8.1 Summary of Key Concepts

In this tutorial, you learned how PHP uses conditional statements to make decisions and control the flow of a program. Here are the key ideas:

  • if statement:
    Runs a block of code only when a condition is true.
    It is the foundation of all conditional logic.

  • else statement:
    Provides an alternative action when the if condition is false.
    It has no condition of its own.

  • elseif statement:
    Allows multiple conditions to be checked in sequence.
    Only the first true condition is executed.

  • Conditional flow:
    PHP evaluates conditions from top to bottom, executing only one matching block.

  • Common mistakes:

    • Forgetting braces {}

    • Using = instead of ==

    • Writing messy or unclear conditions

    • Misusing comparison operators

  • Advanced usage:

    • Nested if statements

    • Combining conditions using &&, ||, and !

    • Real-world applications like login systems, discounts, weather checks, etc.

Overall, understanding conditional statements gives you powerful control over how your PHP programs behave.


8.2 Tips for Writing Clean Conditional Logic

Writing clean, readable conditional code not only prevents bugs but also makes your programs easier to maintain. Here are the best practices:

1. Keep conditions simple

Avoid writing long or complicated conditions inside one if.
If needed, break logic into smaller parts or use variables.

2. Use meaningful variable names

Clear variables make conditions easier to understand.

Example:
$isLoggedIn is better than $x.

3. Always use braces { }

Even for one-line conditions—this prevents accidental bugs.

Good:

if ($age > 18) {
echo "Adult";
}

4. Avoid deep nesting

Too many nested if statements become hard to read.

Instead of this:

if ($a) {
if ($b) {
if ($c) { ... }
}
}

Try:

if ($a && $b && $c) { ... }

Or use elseif where appropriate.

5. Put the most common conditions first

This makes your code faster and easier to follow.

6. Use strict comparisons when needed

Use === instead of == to avoid unexpected type conversions.

7. Use else as a fallback

Always add an else when there’s a possibility of unexpected input.

8. Comment your logic when necessary

Comments help explain complex conditions to future readers (or yourself).