← Back to PHP Course | Chapter 4: Control Flow | Lesson 5 of 14

PHP Nested If

Some decisions depend on more than one independent question -- first check if a user is logged in, and only then check if they have admin rights. A nested if is simply an if statement placed inside the body of another if statement, letting you check a second condition only when the first one has already been satisfied.
Syntax
php
if (outer_condition) {
    if (inner_condition) {
        // runs when both are true
    }
}

Basic Nested If Structure

Placing one if statement inside the body of another creates a nested if -- the outer condition acts as a gate, and the inner condition is only checked at all once execution has already entered the outer block.

Note: Keep nested if blocks shallow (one or two levels) whenever possible; deeper nesting is usually a sign the logic could be restructured.
Warning: An inner if inside an outer if that is false will never run at all -- if you expect the inner check to fire, first confirm the outer condition is actually true.

Example: Basic Nested If Structure

php
<?php
// Declare `$loggedIn`, set to `true`
$loggedIn = true;
// Check whether `$loggedIn`
if ($loggedIn) {
    // Declare `$isAdmin`, set to `true`
    $isAdmin = true;
    // Check whether `$isAdmin`
    if ($isAdmin) {
        // Print "Welcome, admin!" to the output
        echo "Welcome, admin!";
    }
}
?>

Nesting Inside an Else Branch

A nested if can live inside an else block just as easily as inside an if block, letting you handle a completely different set of sub-cases depending on which branch of the outer condition was taken.

Note: Use nesting inside else specifically when the "otherwise" path itself has its own set of distinct sub-cases worth separating.
Warning: Deeply nesting inside both the if AND the else branch of the same outer statement can quickly balloon into a hard-to-follow structure -- consider a switch or match expression instead.

Example: Nesting Inside an Else Branch

php
<?php
// Declare `$loggedIn`, set to `false`
$loggedIn = false;
// Check whether `$loggedIn`
if ($loggedIn) {
    // Print "Welcome back!" to the output
    echo "Welcome back!";
// Otherwise, run this branch
} else {
    // Declare `$hasAccount`, set to `false`
    $hasAccount = false;
    // Check whether `$hasAccount`
    if ($hasAccount) {
        // Print "Please log in." to the output
        echo "Please log in.";
    // Otherwise, run this branch
    } else {
        // Print "Please create an account." to the output
        echo "Please create an account.";
    }
}
?>

When to Combine Conditions with && Instead

If an inner if only ever needs to run when BOTH the outer and inner conditions are true -- with no other combination of outcomes mattering -- combining them into a single if with && produces the exact same behavior with less nesting and less indentation.

Note: Before nesting two if statements, ask whether you actually need to react to the outer-true-inner-false case specially -- if not, && combines them cleanly.
Warning: Combining conditions with && only behaves identically to nesting when there is no code between the outer if and the inner if that needs to run regardless of the inner condition.

Example: When to Combine Conditions with && Instead

php
<?php
// Declare `$age`, set to `20`
$age = 20;
// Declare `$hasTicket`, set to `true`
$hasTicket = true;
// Check whether `$age >= 18 && $hasTicket`
if ($age >= 18 && $hasTicket) {
    // Print "Entry allowed" to the output
    echo "Entry allowed";
}
?>

Nested If for Multi-Step Validation

Nested ifs are a natural fit for multi-step validation, where each step should only be checked if the previous step already passed -- like confirming a form field exists before checking its length, since checking the length of a missing field would cause an error.

Note: Order nested validation checks from "does this exist at all" outward to "is this value specifically correct", so earlier checks protect later ones from operating on missing data.
Warning: Skipping the existence check and jumping straight to a detailed validation rule can cause an error or warning when the value being checked does not exist at all.

Example: Nested If for Multi-Step Validation

php
<?php
// Declare `$field`, set to "hello"
$field = "hello";
// Check whether `isset($field)`
if (isset($field)) {
    // Check whether `strlen($field) > 3`
    if (strlen($field) > 3) {
        // Print "Field is valid." to the output
        echo "Field is valid.";
    }
}
?>

Readability: Alternatives to Deep Nesting

Beyond two or three levels, nested ifs become genuinely hard to follow -- techniques like early returns (exiting a function as soon as a condition fails), combining conditions with &&, or switching to a match/switch expression can flatten deeply nested logic into something much easier to scan.

Note: In a function, an early return for the "invalid" case up front often eliminates an entire level of nesting for the "valid" logic that follows.
Warning: Very deep nesting (four or more levels) is a strong signal the logic should be refactored, not just a style preference -- it becomes genuinely error-prone to maintain.

Example: Readability: Alternatives to Deep Nesting

php
<?php
// Define the function `checkAccess` taking `$age`, `$hasTicket`
function checkAccess($age, $hasTicket) {
    // Check whether `!$hasTicket`
    if (!$hasTicket) {
        // Return `"No ticket"` from this function
        return "No ticket";
    }
    // Check whether `$age < 18`
    if ($age < 18) {
        // Return `"Too young"` from this function
        return "Too young";
    }
    // Return `"Access granted"` from this function
    return "Access granted";
}
// Print `checkAccess(20, true)` to the output
echo checkAccess(20, true);
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Nesting if statements many levels deep, producing a hard-to-follow staircase of indentation instead of combining conditions with && where that would be simpler.
  2. Forgetting that an inner if only ever runs at all if the outer if's condition was true -- a common source of confusion when debugging why a block "never runs".
  3. Misaligning braces in deeply nested blocks, making it hard to tell which closing brace belongs to which if statement.
Chapter Summary
  • A nested if is an if statement written entirely inside the body of another if (or else) block.
  • The inner condition is only ever evaluated if the outer condition was true first.
  • Two or more independent conditions that must ALL be true can often be simplified from nested ifs into a single if with &&.
Browser Support

Nested if statements are a basic language feature supported identically in every PHP version.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.