Menu

← Back to assign.*

Error Identifier: assign.byRefForeachExpr

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);

$array = [1, 2, 3];
foreach ($array as &$item) {
	$item *= 2;
}

$item = 'foo';

Why is it reported? #

After a foreach loop that iterates by reference, the loop variable ($item) remains a reference to the last element of the array. Any subsequent assignment to that variable will overwrite the last element of the array, which is almost always unintentional and a common source of bugs in PHP.

In the example above, after the foreach loop, $item still references $array[2]. Assigning 'foo' to $item changes $array[2] from 6 to 'foo'.

How to fix it #

Unset the reference variable immediately after the foreach loop:

 <?php declare(strict_types = 1);
 
 $array = [1, 2, 3];
 foreach ($array as &$item) {
 	$item *= 2;
 }
+unset($item);

 $item = 'foo';

How to ignore this error #

You can use the identifier assign.byRefForeachExpr to ignore this error using a comment:

// @phpstan-ignore assign.byRefForeachExpr
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: assign.byRefForeachExpr

Rules that report this error #

  • PHPStan\Rules\Variables\AssignToByRefExprFromForeachRule [1]

Edit this page on GitHub

Theme
A
© 2026 PHPStan s.r.o.