The Foreach loop dynamically adds data to the array, and once in the project, foreach needs to dynamically add data to the array (let's give an example here)
Results:
Hey? Strange, this shows that the Foreach loop can dynamically add data to the array, why the $arr data is actually added, but not by the Foreach loop out?
On-line lookup learned that the Foreach loop is actually a copy of the array, not the array itself, if it is an array copy, it must be a copy of the array before the change, according to the results of the operation
Although the loop does change the original array, the loop is a copy of the array (that is, the old array), so you can't loop to the newly added element
All right, let's go.
If you use a reference assignment with a foreach, the newly added data can be recycled.
Results:
and foreach ($arr as & $v) {...} , this method will assign a value instead of copying a value, $v and $arr[$k] point to the same memory address, when the Foreach loop is the original array, the pointer to the array is also moved in the original array, so the newly added data can be recycled, the value of the change will directly affect the value of the array itself
So since &, the Foreach loop is the original array, what about me?
Results:
Since &, the direct operation is the original array, why unset ($v), the original array does not change it?
foreach ($arr as & $v) {...} , equal to $v=& $arr [$k]
$arr [$k] and $v point to $arr[$k] memory address, even if unset ($v), just delete $v to memory space reference, and do not delete $arr[$k] memory address reference, so $arr[$k] is still alive, $arr nature has not changed, So it should be.
Results:
One more thing to pay attention to:& $k what results
Results:
It means: The key cannot be referenced, there is no such syntax format
The above describes the Foreach loop dynamic to add data to the array, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.