Home >Backend Development >PHP Tutorial >Dynamically add data to the array during foreach loop
Dynamicly add data to the array during the foreach loop. Once when I was working on a project, I needed to dynamically add data to the array during the foreach (let’s give an example here)
Result:
Hey? It's strange. This shows that data can be dynamically added to the array during the foreach loop. Why is the data in $arr indeed added, but not out by the foreach loop?
I searched online and learned that what the foreach loop actually does is a copy of the array, not the array itself. If it is an array copy, it must be a copy made before changing the array. According to the running results,
Although the original value is indeed changed in the loop array, but the loop is a copied array (that is, the old array), so you cannot loop to the newly added elements
Okay, bear with it for now
If you use reference assignment during foreach, the newly added data can be The loop comes out
The result:
And when foreach ($arr as &$v){···}, this method will assign a value by reference instead of copying a value, $v and $arr [$k] points to the same memory address. At this time, the foreach loop is the original array. The pointer of the array is also moved in the original array, so the newly added data can be looped out, and the change in value also directly affects the value of the array itself
That Since when using &, foreach directly loops through the original array, what about me?
Result:
Since & is directly operating on the original array, why does the original array remain unchanged after unset($v)? When
foreach ($arr as &$v){···}, it is equivalent to $v=&$arr[$k]
$arr[$k] and $v point to $arr[$k] at the same time The memory address, even unset($v), only deletes the reference of $v to the memory space, and does not delete the reference of $arr[$k] to the memory address, so $arr[$k] is still alive, $ arr naturally does not change, so it should be like this
Result:
Another thing to note: &$k What result
Result:
means: the key cannot Being quoted, there is no such grammatical format at all
The above introduces the dynamic addition of data to the array during the foreach loop, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.