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> $items
*/
function doFoo(array $items): void
{
foreach ($items as $value) {
$value = rand();
echo $value;
}
}
Why is it reported? #
The foreach loop binds each element to $value, but the loop body assigns a new value to $value before reading it. The element bound by the loop is never observed. This usually points to a logic error — the element was meant to be used — or to a variable name accidentally reused for a different value.
This is different from foreach.unusedValue, where the value 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 element before overwriting the variable, or use it in the computation:
foreach ($items as $value) {
- $value = rand();
+ $value = $value + rand();
echo $value;
}
Use a different variable for the new value so the element is not lost:
foreach ($items as $value) {
- $value = rand();
- echo $value;
+ $random = rand();
+ echo $value, $random;
}
How to ignore this error #
You can use the identifier foreach.valueOverwritten to ignore this error using a comment:
// @phpstan-ignore foreach.valueOverwritten
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.valueOverwritten
Rules that report this error #
- PHPStan\Rules\DeadCode\UnusedVariableRule [1]