Skip to content

ForeachOverNonIterable ​

warning native on by default

Group: Probable bugs

Report a foreach over a value that the code itself shows is neither an array nor an object. PHP raises a warning and skips the loop.

Example ​

php
<?php
function total(int $count): void
{
    foreach ($count as $item) {
    }
}

Reported:

  • line 4: Iterate over an array or an object, not int.

Detection ​

  • The subject of a foreach.
  • The type of the subject comes from native declarations only, and every member of it is an int, a float, a string, a bool or null.

Exceptions (no report) ​

  • A subject of unknown type, or one that may be an array, an object, iterable, callable or mixed: a foreach walks the properties of any object.
  • A type that comes only from PHPDoc, which DocumentedForeachOverNonIterable covers.

Fix ​

None.

PHP versions ​

No gating.

Configure ​

In custos.json:

json
{
  "rules": {
    "ForeachOverNonIterable": {
      "enabled": false
    }
  }
}

Suppress ​

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

php
// @custos-ignore ForeachOverNonIterable

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