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) {
$key = 'prefix';
echo $key, $value;
}
}
Why is it reported? #
The foreach loop binds each element’s key to $key, but the loop body assigns a new value to $key before reading it. The key bound by the loop is never observed. This usually points to a logic error — the key was meant to be used — or to a variable name accidentally reused for a different value.
This is different from foreach.unusedKey, where the key variable is simply never read. Here an assignment in the loop body overwrites it first.
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 key in the computation instead of discarding it:
foreach ($data as $key => $value) {
- $key = 'prefix';
+ $key = 'prefix' . $key;
echo $key, $value;
}
If the key is not needed, drop it from the foreach and use a separate variable:
- foreach ($data as $key => $value) {
- $key = 'prefix';
- echo $key, $value;
+ foreach ($data as $value) {
+ $prefix = 'prefix';
+ echo $prefix, $value;
}
How to ignore this error #
You can use the identifier foreach.keyOverwritten to ignore this error using a comment:
// @phpstan-ignore foreach.keyOverwritten
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.keyOverwritten
Rules that report this error #
- PHPStan\Rules\DeadCode\UnusedVariableRule [1]