foreach modify



1. The foreach() loop no longer works on the internal pointers of the array.

$array = [0, 1, 2];
foreach ($array as &$val) 
{
    var_dump(current($array));
}
PHP7 will print int(0) three times as a result, which means that the internal pointer of the array has not changed.

The results of the previous operation will print int(1), int(2) and bool(false)

2. When looping according to the value, foreach is a copy operation of the array

When foreach loops by value (by-value), foreach operates on a copy of the array. In this way, modifications to the array during the loop will not affect the loop behavior.
$array = [0, 1, 2];
$ref =& $array; // Necessary to trigger the old behavior
foreach ($array as $val) {
    var_dump($val);
    unset($array[1]);
}
Although the above code unsets the second element of the array in the loop, PHP7 will still print out the three elements: (0 1 2)

The previous version of PHP would skip 1 , only print (0 2).

3. When looping according to references, modifications to the array will affect the loop.

If you use a reference when looping, modifications to the array will affect the loop behavior. However, the PHP7 version optimizes the maintenance of locations under many scenarios. For example, appending elements to an array while looping.

$array = [0];
foreach ($array as &$val) {
    var_dump($val);
    $array[1] = 1;
}

The appended elements in the above code will also participate in the loop, so PHP7 will print "int(0) int(1)", and the old version will only print "int(0)".

4. Looping over simple objects plain (non-Traversable).

Looping over simple objects, whether looping by value or looping by reference, behaves the same as looping by reference in an array. However, location management will be more precise.

5. The object behavior for Traversable objects is the same as before.

Editor's note: stackoverflow's explanation above: Traversable object is one that implements Iterator or IteratorAggregate interface. If an object implements the iterator or IteratorAggregate interface, it can be called an iterator object.