Nested If

ID

php.nested_if

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Complexity

Language

Php

Tags

complexity, readability

Description

Reports an if statement whose nesting depth — the number of enclosing if statements within the same function — exceeds a configurable threshold (maxDepth, default 4). An elseif or else continuation is a sibling branch of the same if, not a deeper level, and does not add to the depth.

Rationale

Each additional level of nested if multiplies the number of paths a reader must hold in mind and the number of cases a test must cover. Past a handful of levels the logic becomes hard to follow and easy to get subtly wrong. Guard clauses, early returns, and extracting the inner branch into a well-named method flatten the structure and make each condition stand on its own.

<?php
// FLAW — nested 5 levels deep with the default limit of 4
if ($a > 0) {
    if ($b > 0) {
        if ($c > 0) {
            if ($d > 0) {
                if ($e > 0) {
                    doWork();
                }
            }
        }
    }
}

// OK — a guard-clause rewrite keeps every branch shallow
if ($a <= 0 || $b <= 0 || $c <= 0 || $d <= 0 || $e <= 0) {
    return;
}
doWork();

Remediation

Reduce the nesting: combine conditions with &&, invert a condition into an early return or continue, or extract the innermost block into a separate method. Raise maxDepth only when a deeper structure is genuinely warranted.