Technology

The Foreach Bug in PHP

Exploring an unexpected behavior in PHP with foreach loops when iterating by reference vs by value, causing array elements to unexpectedly change.

Sangrak

Code Snippet 1

$array = array('a','b','c','d','e','f');

foreach($array as &$v) {
	echo $v;
}

echo PHP_EOL;

foreach($array as $v) {
  echo $v;
}

Iterating through an array twice, first by reference and then by value, yields an unexpected result:

abcdef
abcdee

This phenomenon occurs because PHP does not have variable declarations separate from usage, and variables are not localized to code blocks.

Why did 'e' appear last, instead of 'a' or 'b'? Running the following code snippet sheds some light on this.

Code Snippet 2

function prettyPrintArray($array) {
	foreach($array as $_v) echo "{$_v}";
	echo PHP_EOL;
}

$array = array('a','b','c','d','e','f');

foreach($array as &$v) { }

foreach($array as $v) {
	prettyPrintArray($array);
}

$v = "test";
prettyPrintArray($array);

The outcome:

abcdea
abcdeb
abcdec
abcded
abcdee
abcdee
abcdetest

The issue stems from the $v in the first foreach retaining its reference property, influencing the code to the very end. This arises from PHP's failure to reset $v's properties when starting a new foreach loop. For better understanding, compare Code Snippet 3 with Code Snippet 2.

Code Snippet 3

function prettyPrintArray($array) {
	foreach($array as $_v) echo "{$_v}";
	echo PHP_EOL;
}

$array = ['a','b','c','d','e','f'];

foreach($array as &$v)
	echo $v;

$v = "test";

echo PHP_EOL;

prettyPrintArray($v);

By iterating and modifying the assigned $value, the last element of the array gets changed:

abcdef
abcdetest

Solving this problem temporarily can be achieved by unsetting the variable after the foreach loop.

More on this topic