Error Identifier: foreach.valueOverwrite
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);
function process(array $items, string $value): void
{
foreach ($items as $value) {
echo $value;
}
}
Why is it reported? #
This error is reported by phpstan-strict-rules.
The value variable of a foreach loop overwrites a variable that already exists in the current scope. The previous value of the variable is lost when the loop starts iterating, which is usually unintentional and can lead to bugs.
In the example above, the parameter $value is overwritten by the foreach loop value variable, discarding the value that was passed to the function.
How to fix it #
Use a different variable name for the loop value:
function process(array $items, string $value): void
{
- foreach ($items as $value) {
- echo $value;
+ foreach ($items as $item) {
+ echo $item;
}
}
Or remove the conflicting variable from the outer scope if it is not needed:
-function process(array $items, string $value): void
+function process(array $items): void
{
foreach ($items as $value) {
echo $value;
}
}
How to ignore this error #
You can use the identifier foreach.valueOverwrite to ignore this error using a comment:
// @phpstan-ignore foreach.valueOverwrite
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.valueOverwrite
Rules that report this error #
- PHPStan\Rules\ForeachLoop\OverwriteVariablesWithForeachRule [1] phpstan/phpstan-strict-rules