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...

  1. Consider the following block of code:
    $a = [1, 2, 3];
    foreach ($a as $v) {
      printf("%2d\n", $v);
      unset($a[1]);
    }
  2. In both PHP 5 and 7, the output would appear ...

Get PHP 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.