diff --git a/src/Psalm/Checker/Statements/Block/ForeachChecker.php b/src/Psalm/Checker/Statements/Block/ForeachChecker.php index c05f670bb..26875948a 100644 --- a/src/Psalm/Checker/Statements/Block/ForeachChecker.php +++ b/src/Psalm/Checker/Statements/Block/ForeachChecker.php @@ -376,6 +376,11 @@ class ForeachChecker $location, $foreach_context->branch_point ); + } else { + $statements_checker->registerVariableAssignment( + $key_var_id, + $location + ); } if ($stmt->byRef && $context->collect_references) { diff --git a/tests/UnusedVariableTest.php b/tests/UnusedVariableTest.php index 01254bd80..e25d7c694 100644 --- a/tests/UnusedVariableTest.php +++ b/tests/UnusedVariableTest.php @@ -1314,6 +1314,19 @@ class UnusedVariableTest extends TestCase echo $a;', 'error_message' => 'UnusedVariable', ], + 'reusedKeyVar' => [ + ' "foo.foo"]; + + foreach ($arr as $key => $v) { + list($key) = explode(".", $v); + echo $key; + }', + 'error_message' => 'UnusedVariable', + ], ]; } }