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 array<string, int> $data
*/
function doFoo(array $data): void
{
foreach ($data as $key => $value) {
echo $value;
}
}
Why is it reported? #
The foreach loop binds each element’s key to $key, but the loop body never reads it. Capturing a key that nobody uses is unnecessary. This often means the body should use $key but doesn’t, or the key does not need to be captured at all.
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 #
Drop the key from the foreach if only the value is needed:
- foreach ($data as $key => $value) {
+ foreach ($data as $value) {
echo $value;
}
Or use the key in the loop body if it was intended to be read:
foreach ($data as $key => $value) {
+ echo $key;
echo $value;
}
If you deliberately want to keep the key variable, prefix its name with an underscore. PHPStan ignores variables whose name starts with _:
- foreach ($data as $key => $value) {
+ foreach ($data as $_key => $value) {
echo $value;
}
How to ignore this error #
You can use the identifier foreach.unusedKey to ignore this error using a comment:
// @phpstan-ignore foreach.unusedKey
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.unusedKey
Rules that report this error #
- PHPStan\Rules\DeadCode\UnusedVariableRule [1]