Skip to content

DocumentedForeachOverNonIterable ​

warning native off by default

Group: Probable bugs

Report a foreach over a value that PHPDoc says is neither an array nor an object. The loop may still run, since PHP does not check PHPDoc, but the loop and the documentation disagree. Subjects the code alone proves are not iterable are ForeachOverNonIterable's.

Example ​

php
<?php
/** @param string $names */
function greet($names): void
{
    foreach ($names as $name) {
    }
}

Reported:

  • line 5: Iterate over an array or an object, not string.

Detection ​

  • The subject of a foreach.
  • The type of the subject is the one PHPDoc-aware inference gives: @param, @var, @return and @property tags count.
  • Every member of that type is an int, a float, a string, a bool or null.

Exceptions (no report) ​

  • Subjects ForeachOverNonIterable reports.
  • A subject of unknown type, or one that may be an array, an object, iterable, callable or mixed.
  • A subject whose PHPDoc type the code contradicts: when the code alone gives the subject a type that no value of the PHPDoc type fits (/** @var int $x */ over $x = new Order()), the tag is stale.
  • $this inside a closure or an arrow function, which may be bound to an object of another class.

Fix ​

None: either the loop or the documentation is wrong.

PHP versions ​

No gating.

Configure ​

In custos.json:

json
{
  "rules": {
    "DocumentedForeachOverNonIterable": {
      "enabled": true
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file):

php
// @custos-ignore DocumentedForeachOverNonIterable

Released under the MIT License. Native rules and rules modeled on Php Inspections (EA Extended); independent clean-room implementation.