0
0
PHPprogramming~5 mins

Nested conditional execution in PHP

Choose your learning style9 modes available
Introduction

Nested conditional execution lets you check one condition inside another. This helps make decisions step-by-step.

When you want to check if a number is positive, negative, or zero.
When you need to decide a price discount based on customer type and purchase amount.
When you want to check multiple levels of user permissions before allowing access.
When you want to handle different cases inside a main condition, like checking weather and time.
Syntax
PHP
<?php
if (condition1) {
    if (condition2) {
        // code if both condition1 and condition2 are true
    } else {
        // code if condition1 is true but condition2 is false
    }
} else {
    // code if condition1 is false
}
?>
You can put one if statement inside another to check more detailed conditions.
Use curly braces { } to group the code inside each condition clearly.
Examples
This checks if a number is positive. Inside that, it checks if it is even or odd.
PHP
<?php
$number = 10;
if ($number > 0) {
    if ($number % 2 == 0) {
        echo "Positive even number";
    } else {
        echo "Positive odd number";
    }
} else {
    echo "Not a positive number";
}
?>
This checks if a person is an adult or minor. If adult, it further checks if senior.
PHP
<?php
$age = 20;
if ($age >= 18) {
    if ($age >= 65) {
        echo "Senior adult";
    } else {
        echo "Adult";
    }
} else {
    echo "Minor";
}
?>
Sample Program

This program assigns a grade based on the score. It first checks if the score is passing (50 or more). Then it checks for A, B, or C grades inside the passing scores.

PHP
<?php
$score = 75;
if ($score >= 50) {
    if ($score >= 90) {
        echo "Grade: A";
    } elseif ($score >= 70) {
        echo "Grade: B";
    } else {
        echo "Grade: C";
    }
} else {
    echo "Failed";
}
?>
OutputSuccess
Important Notes

Always indent nested conditions to keep your code easy to read.

Too many nested conditions can make code hard to follow. Consider other ways if it gets too deep.

Summary

Nested conditionals let you check one condition inside another.

Use them to make detailed decisions step-by-step.

Keep your code clean and readable with proper indentation.