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> $data
*/
function doFoo(array $data): int
{
$count = 0;
foreach ($data as $value) {
$count++;
}
return $count;
}
Why is it reported? #
The foreach loop binds each element to $value, but the loop body never reads it. Assigning a value that nobody uses has no effect. This often means the body should use $value but doesn’t.
When the loop also binds a key (foreach ($data as $key => $value)) and only the key is used, the unused value is not reported, because PHP has no syntax for binding just the key.
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 in the loop body if it was intended to be read:
foreach ($data as $value) {
- $count++;
+ $count += $value;
}
If the loop only counts or repeats something, a function like count() may express the intent more directly:
- $count = 0;
- foreach ($data as $value) {
- $count++;
- }
-
- return $count;
+ return count($data);
If you deliberately want to keep the value variable, prefix its name with an underscore. PHPStan ignores variables whose name starts with _:
- foreach ($data as $value) {
+ foreach ($data as $_value) {
$count++;
}
How to ignore this error #
You can use the identifier foreach.unusedValue to ignore this error using a comment:
// @phpstan-ignore foreach.unusedValue
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.unusedValue
Rules that report this error #
- PHPStan\Rules\DeadCode\UnusedVariableRule [1]