PHP7 new features foreach modification example introduction, php7foreach
1. The foreach () loop no longer works on the internal pointer of the array,Before PHP 7, when the array is iterated through foreach, the array pointer will move. For more information, see the following code ..
$array = [0, 1, 2];foreach ($array as &$val) {var_dump(current($array));}
The result of PHP5 running will print int (1) int (2) bool (false)
The results of PHP 7 run will print three int (0) times, that is, the internal pointer of the array has not changed.
The running result prints int (1), int (2), and bool (false)
2. When looping by value, foreach copies the array.
When foreach loops by value, foreach performs a copy operation on the array. In this way, the changes made to the array during the loop process will not affect the loop behavior.
$array = [0, 1, 2];$ref =& $array; // Necessary to trigger the old behaviorforeach ($array as $val) {var_dump($val);unset($array[1]);}
Although the above Code unsets the second element of the array in a loop, PHP 7 still prints the three elements: (0 1 2)
Earlier versions of PHP will skip 1 and only print (0 2 ).
3. When looping by reference, modifying the array will affect the loop.
If the array is referenced during the loop, modifying the array will affect the loop behavior. However, PHP7 optimizes the maintenance of the following locations in many scenarios. For example, append an element to the array during loop.
$array = [0];foreach ($array as &$val) {var_dump($val);$array[1] = 1;}
The elements appended to the code above will also participate in the loop, so that PHP7 will print "int (0) int (1)", the old version will only print "int (0 )".
4. Loop of a simple object plain (non-Traversable.
The loop of a simple object, whether by value or by reference, is the same as that of the array loop by reference. However, location management is more accurate.
5. The behavior of the Traversable objects object is consistent with that of the previous object.
Editor's note: stackoverflow explained above: Traversable object is one that implements Iterator or IteratorAggregate interface. If an object implements the iterator or IteratorAggregate interface, it is called an iteration object.
The preceding section describes the new features of PHP 7 foreach. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!