Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
/**
* @param list<int> $numbers
*/
function doFoo(array $numbers): void
{
foreach ($numbers as $value) {
while (rand(0, 1)) {
$value = $value + 1;
}
}
}
Why is it reported? #
The foreach loop binds each element to $value, and that value is read — but only by $value = $value + 1, whose result no code ever observes. The value feeds a closed computation that produces nothing.
This is different from foreach.unusedValue, where the value variable is never read at all. Here the value flows through further computation, but that computation is itself dead, so the whole chain has no effect. This often means the loop body should use $value for something observable but doesn’t, or the loop only needs the keys.
This rule is part of PHPStan’s dead code analysis. It is reported at rule level 4 and above, and is currently part of Bleeding Edge.
How to fix it #
Use the value for something observable if that was the intent:
foreach ($numbers as $value) {
while (rand(0, 1)) {
$value = $value + 1;
}
+ echo $value;
}
Or drop the loop entirely if it does nothing:
- foreach ($numbers as $value) {
- while (rand(0, 1)) {
- $value = $value + 1;
- }
- }
How to ignore this error #
You can use the identifier foreach.unusedValueFlow to ignore this error using a comment:
// @phpstan-ignore foreach.unusedValueFlow
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: foreach.unusedValueFlow
Rules that report this error #
- PHPStan\Rules\DeadCode\UnusedVariableRule [1]