Menu

Error Identifier: foreach.unusedKeyFlow

← Back to foreach.*

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;
		while (rand(0, 1)) {
			$key = $key . '!';
		}
	}
}

Why is it reported? #

The foreach loop binds each element’s key to $key, and that key is read — but only by $key = $key . '!', whose result no code ever observes. The key feeds a closed computation that produces nothing.

This is different from foreach.unusedKey, where the key variable is never read at all. Here the key flows through further computation, but that computation is itself dead, so the whole chain has no effect. This often means the loop body should use $key for something observable 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 #

Use the key for something observable if that was the intent:

 	foreach ($data as $key => $value) {
 		echo $value;
 		while (rand(0, 1)) {
 			$key = $key . '!';
+			echo $key;
 		}
 	}

Or drop the key from the foreach if only the value is needed:

-	foreach ($data as $key => $value) {
+	foreach ($data as $value) {
 		echo $value;
-		while (rand(0, 1)) {
-			$key = $key . '!';
-		}
 	}

How to ignore this error #

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

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

Rules that report this error #

  • PHPStan\Rules\DeadCode\UnusedVariableRule [1]
Theme
A
© 2026 PHPStan s.r.o.