Skip to content

SuspiciousLoop ​

error on by default

Group: Probable bugs · PhpStorm name: SuspiciousLoopInspection

Two loop mistakes: a for condition section with several comma-separated expressions (only the last one decides whether the loop continues), and loop variables that silently overwrite a parameter of the enclosing function or the variable of an outer loop.

Example ​

php
<?php
for ($n = 0; $n < 5, $n != 3; $n++) {}

function scan(array $rows, $pos) {
    foreach ($rows as $rows) {}
    for ($pos = 1; $pos < 3; $pos++) {}
    foreach ($rows as $r) {}
}

class Grid {
    public function walk($cell) {
        foreach ([1, 2] as $cell) {}
    }
}

foreach ($matrix as $row => $cols) {
    for ($row = 0, $k = 1; $row < 2; $row++) {}
    while ($cols) {
        foreach ($cols as $cols) {}
    }
    array_map(function () {
        foreach ([] as $row) {}
    }, []);
    foreach ($cols as $c) {}
}

Reported:

  • line 2: Only the last expression of the 'for' condition is evaluated as the condition; combine them with && or ||.
  • line 5: Loop variable '$rows' overwrites a function parameter.
  • line 6: Loop variable '$pos' overwrites a function parameter.
  • line 12: Loop variable '$cell' overwrites a method parameter.
  • line 17: Loop variable '$row' overwrites a variable of an outer loop.
  • line 19: Loop variable '$cols' overwrites a variable of an outer loop.

Options ​

OptionTypeDefaultEffect
VERIFY_VARIABLES_OVERRIDEbooltrueEnables the parameter and outer-loop clash checks (D2–D4).

Configure ​

In custos.json:

json
{
  "rules": {
    "SuspiciousLoop": {
      "enabled": false,
      "options": {
        "VERIFY_VARIABLES_OVERRIDE": true
      }
    }
  }
}

Suppress ​

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

php
// @custos-ignore SuspiciousLoop

/**
 * @noinspection SuspiciousLoopInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.