Unreachable Code

ID

php.unreachable_code

Severity

low

Remediation Complexity

auto_fix

Remediation Risk

low

Remediation Effort

low

Resource

Dead Code

Language

Php

Tags

dead-code, reliability

Description

Reports a statement that can never execute because control flow always leaves the enclosing region before reaching it. The analysis walks the routine’s control-flow graph: code becomes unreachable after an unconditional jump (return, throw, break, continue, goto), after a process-terminating call (exit / die), or inside an always-taken constant branch. Only the first statement of each dead region is flagged.

Rationale

Code after an unconditional exit is dead: it will never run regardless of input. Its presence is almost always a mistake — a misplaced statement, an early return left in during debugging, or a refactor that stranded logic below the exit. Dead code misleads readers into thinking it runs and hides the real behaviour of the routine.

The analysis is control-flow aware, so it does not mistake a conditionally-reached statement for dead code: a return inside one branch of an if does not make the code after the if unreachable.

<?php
function afterReturn(int $n): int
{
    return $n * 2;
    $n = 0;            // FLAW — never executed; the return already left the function
}

function clean(int $n): int
{
    if ($n > 0) {
        return $n;     // OK — return is the last statement in its branch
    }
    return 0;          // OK — reachable when $n <= 0
}

Remediation

Delete the unreachable statement, or — if it was meant to run — move it above the exit or restructure the control flow (for example, guard the exit behind a condition) so the logic is reached.