Today, a colleague wrote a code similar to the following:
$a = array(1, 2, 3);foreach($a as $k => &$v){ $a[] = $v;}
The default 128M memory is simply blown up, for the simple reason that each loop is $a incremented by a k-v, resulting in an infinite loop in which memory is not enough.
The key is not here, the key is to be $k => &$v changed $k => $v , the cycle can be normal execution.
Check out the PHP manual with the phrase:"NOTE: Unless the array is referenced, foreach operates on a copy of the specified array, not the array itself. "
Is it because the second type of foreach operation is a copy of the array $a , and the first one is the $a reference or itself?
Otherwise, this logic error should be two kinds of writing will be reflected in it.
Reply content:
Today, a colleague wrote a code similar to the following:
$a = array(1, 2, 3);foreach($a as $k => &$v){ $a[] = $v;}
The default 128M memory is simply blown up, for the simple reason that each loop is $a incremented by a k-v, resulting in an infinite loop in which memory is not enough.
The key is not here, the key is to be $k => &$v changed $k => $v , the cycle can be normal execution.
Check out the PHP manual with the phrase:"NOTE: Unless the array is referenced, foreach operates on a copy of the specified array, not the array itself. "
Is it because the second type of foreach operation is a copy of the array $a , and the first one is the $a reference or itself?
Otherwise, this logic error should be two kinds of writing will be reflected in it.
Answer
First of all, be sure your answer, the reason is also the same as you say, PHP refers to the difference between the transfer and value delivery. As for debugging, I recommend using Xdebug to debug, print the ZVAL structure of the array, the code is as follows:
&$value) { $arr[] = $value; xdebug_debug_zval('arr'); echo "\n";}
You can see the members of the ZVAL structure: arr: (refcount=3, isref=1),the IS ref field is 1 description is a reference to ARR
New questions
I should be relieved to review the algorithm, prepare a variety of school strokes written, but helpless test an array of elements, code:
&$value) { $arr[] = $value; xdebug_debug_zval('arr'); echo "\n";}
This is not the same as I want to go into the dead loop, consider whether it is a foreach internal implementation mechanism caused by, ask for explanation!!