In certain relatively obscure circumstances, the behavior of code inside a foreach() loop will vary between PHP 5 and PHP 7. First of all, there have been massive internal improvements, which means that in terms of sheer speed, processing inside the foreach() loop will be much faster running under PHP 7, compared with PHP 5. Problems that are noticed in PHP 5 include the use of current(), and unset() on the array inside the foreach() loop. Other problems have to do with passing values by reference while manipulating the array itself.
$a = [1, 2, 3];
foreach ($a as $v) {
printf("%2d\n", $v);
unset($a[1]);
}1 2 3
$a = [1, 2, 3];
$b = &$a;
foreach ($a as $v) {
printf("%2d\n", $v);
unset($a[1]);
}|
PHP 5 |
PHP 7 |
|---|---|
|
1 3 |
1 2 3 |
$a = [1,2,3];
foreach($a as &$v) {
printf("%2d - %2d\n", $v, current($a));
}|
PHP 5 |
PHP 7 |
|---|---|
|
1 - 2 2 - 3 3 - 0 |
1 - 1 2 - 1 3 - 1 |
foreach() loop, once the array iteration by reference is complete, is also problematic in PHP 5. This behavior has been made consistent in PHP 7. The following code example demonstrates this:$a = [1];
foreach($a as &$v) {
printf("%2d -\n", $v);
$a[1]=2;
}|
PHP 5 |
PHP 7 |
|---|---|
|
1 - |
1 - 2- |
array_push(), array_pop(), array_shift(), and array_unshift().Have a look at this example:
$a=[1,2,3,4];
foreach($a as &$v) {
echo "$v\n";
array_pop($a);
}|
PHP 5 |
PHP 7 |
|---|---|
|
1 2 1 1 |
1 2 |
foreach() loop, which itself iterates on the same array by reference. In PHP 5 this construct simply did not work. In PHP 7 this has been fixed. The following block of code demonstrates this behavior:$a = [0, 1, 2, 3];
foreach ($a as &$x) {
foreach ($a as &$y) {
echo "$x - $y\n";
if ($x == 0 && $y == 1) {
unset($a[1]);
unset($a[2]);
}
}
}|
PHP 5 |
PHP 7 |
|---|---|
|
0 - 0 0 - 1 0 - 3 |
0 - 0 0 - 1 0 - 3 3 - 0 3 -3 |
Add these code examples to a single PHP file, chap_02_foreach.php. Run the script under PHP 5 from the command line. The expected output is as follows:

Run the same script under PHP 7 and notice the difference:

For more information, consult the RFC addressing this issue, which was accepted. A write-up on this RFC can be found at: https://wiki.php.net/rfc/php7_foreach.