Understanding differences in foreach() handling
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.
How to do it...
- Consider the following block of code:
$a = [1, 2, 3]; foreach ($a as $v) { printf("%2d\n", $v); unset($a[1]); }
- In both PHP 5 and 7, the output would appear as follows:
1 2 3
- If you add an assignment before the loop, however, the behavior changes:
$a = [1, 2, 3]; $b = &$a; foreach ($a as $v) { printf("%2d\n", $v); unset($a[1]); }
- Compare the output of PHP 5 and 7:
PHP...