Menu

← Back to foreach.*

Error Identifier: foreach.keyOverwrite

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 $key): void
{
	foreach ($items as $key => $value) {
		echo $key . ': ' . $value;
	}
}

Why is it reported? #

This error is reported by phpstan/phpstan-strict-rules.

The key 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 $key is overwritten by the foreach loop key variable, discarding the value that was passed to the function.

How to fix it #

Use a different variable name for the loop key:

 <?php declare(strict_types = 1);
 
 function process(array $items, string $key): void
 {
-	foreach ($items as $key => $value) {
-		echo $key . ': ' . $value;
+	foreach ($items as $k => $value) {
+		echo $k . ': ' . $value;
 	}
 }

Or remove the conflicting variable from the outer scope if it is not needed:

 <?php declare(strict_types = 1);
 
-function process(array $items, string $key): void
+function process(array $items): void
 {
 	foreach ($items as $key => $value) {
 		echo $key . ': ' . $value;
 	}
 }

How to ignore this error #

You can use the identifier foreach.keyOverwrite to ignore this error using a comment:

// @phpstan-ignore foreach.keyOverwrite
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.keyOverwrite

Rules that report this error #

  • PHPStan\Rules\ForeachLoop\OverwriteVariablesWithForeachRule [1] phpstan/phpstan-strict-rules

Edit this page on GitHub

Theme
A
© 2026 PHPStan s.r.o.