LoopWhichDoesNotLoop
warning on by defaultGroup: Control flow · PhpStorm name: LoopWhichDoesNotLoopInspection
A loop whose body always leaves on the first pass (its last statement is break, return or throw and nothing continues it), or whose body is empty, never actually iterates. It is either a bug or a disguised if / "take first element" idiom.
Example
php
<?php
foreach ($queue as $job) {
process($job);
break;
}
for ($t = 0; $t < 5; $t++) {
return $t;
}
while (poll()) {
throw new \LogicException('stop');
}
do {
break 1;
} while ($again);
while (wait()) {
// nothing yet
}
foreach ($grid as $line) {
foreach ($line as $cell) {
while (true) {
continue 2; // continues the middle loop, not the outer one
}
}
break;
}
foreach ($grid as $line) {
foreach ($line as $cell) {
continue 2; // continues the outer loop
}
break;
}
foreach ($grid as $line) {
if (!$line) { continue; }
break;
}
while ($ok) {
step();
}
/** @var \Iterator $cursor */
foreach ($cursor as $first) {
break;
}
while ($ok) break;Reported:
- line 2: Loop body exits on the first iteration; the loop never repeats.
- line 6: Loop body exits on the first iteration; the loop never repeats.
- line 9: Loop body exits on the first iteration; the loop never repeats.
- line 12: Loop body exits on the first iteration; the loop never repeats.
- line 15: Loop body exits on the first iteration; the loop never repeats.
- line 18: Loop body exits on the first iteration; the loop never repeats.
Configure
In custos.json:
json
{
"rules": {
"LoopWhichDoesNotLoop": {
"enabled": false
}
}
}Suppress
Before the statement or declaration (or the first statement of the file), either of:
php
// @custos-ignore LoopWhichDoesNotLoop
/**
* @noinspection LoopWhichDoesNotLoopInspection
*/