Empty Loop Body

ID

php.empty_loop_body

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

CWE:1071, reliability, suspicious

Description

Reports a for, foreach, while or do/while loop whose body contains no statements. This covers the empty brace block (for (…​) { }), the bare-semicolon body (while (…​) ;) and the alternative-syntax block (while (…​): endwhile;).

Rationale

An empty loop body is almost always a defect: the work the loop was meant to perform is missing, or it was deleted and the surrounding loop left behind. Where the iteration is genuinely driven by side effects in the condition (for example advancing a pointer), the empty body hides that intent and reads as a mistake. Making the loop body explicit — or removing the loop — eliminates the ambiguity.

<?php
for ($i = 0; $i < count($rows); $i++) {   // FLAW — body never does anything
}

while ($line = fgets($fh)) {              // OK — does work each iteration
    process($line);
}

Remediation

Add the missing statements to the loop body. If the loop only exists to consume a generator or advance a cursor through its condition, move that side effect into the body so the intent is explicit, or replace the loop with a clearer construct. If the loop is redundant, delete it.