foreach in PHP
If the is_ref of the array is 1, the original array is directly looped
If foreach ($arr as & $v) {} will eventually set the is_ref of $arr to 1, loop the original array directly
If the array is_ref is 0, but the reference count is greater than 1, the array is copied and the new memory space is opened, looping the copied array
Is there a problem with that?
There's a more tangled problem.
At the beginning of the foreach, the array reference is counted +1, and then when the array changes, $arr [$k]=111 or run current functions, copy on Write
Or at the beginning of the foreach array, the reference count was not +1, but the array was changed ($arr [$k]=111, running current, etc.) to replicate an array, opening up new memory space.
Of course, the execution of the code seems to be the same regardless of how it's done.
But prepare documents and share them, so as not to mislead
Here, thank you first.
Reply content:
foreach in PHP
If the is_ref of the array is 1, the original array is directly looped
If foreach ($arr as & $v) {} will eventually set the is_ref of $arr to 1, loop the original array directly
If the array is_ref is 0, but the reference count is greater than 1, the array is copied and the new memory space is opened, looping the copied array
Is there a problem with that?
There's a more tangled problem.
At the beginning of the foreach, the array reference is counted +1, and then when the array changes, $arr [$k]=111 or run current functions, copy on Write
Or at the beginning of the foreach array, the reference count was not +1, but the array was changed ($arr [$k]=111, running current, etc.) to replicate an array, opening up new memory space.
Of course, the execution of the code seems to be the same regardless of how it's done.
But prepare documents and share them, so as not to mislead
Here, thank you first.
Solution: http://segmentfault.com/a/1190000004340640
You are so messy ... The problem is so hard to find ...
Are you talking about is_ref in the definition of Zval is_ref?
Found in the two problems, seemingly and zval copy on write, I simply answer the copy on the write mechanism. (This is based on PHP 5, in PHP 7 zval structure changes very much, another matter)
A push variable increases refcount to indicate that there are more variables that use this value, such as an array in foreach, and if the increment of refcount to 2 means that the HashTable in the value Zval.value is used in two variables, then replication does not happen immediately. Instead of modifying the variable, if RefCount > 1 is detected (indicating that there are other variables referencing the HashTable), it is necessary to first copy the HashTable and modify it.
Should indicate version 7 changed, in order to avoid trouble I try to use the array walk