I encountered a problem about the PHP foreach reference at work.
Simply put, the following code
$arr=array(‘a‘,‘b‘,‘c‘ ,‘d‘);foreach($arr as $k=>&$v){ ........} foreach($arr as $k=>$v){........} print_r($arr);
The result is
A
B
C
C
Refer to this article and this article
After the first foreach traversal, the value of $ V is 'D' and the corresponding key is 3. Note that $ V is referenced here.
When the second foreach traverses the first element, $ v = 'A', then according to the reference, $ arr [3] = 'A'
The value of $ arr is
0
1 B
2 C
3
When traversing the second element, $ v = 'B', then according to the reference, $ arr [3] = 'B'
The value of $ arr is
0
1 B
2 C
3 B
When traversing the third element, $ v = 'C', then according to the reference, $ arr [3] = 'C'
The value of $ arr is
0
1 B
2 C
3 C
When traversing the third element, $ v = 'C', then according to the reference, $ arr [3] = 'C'
At this time, the value of $ arr is, and it remains unchanged
0
1 B
2 C
3 C
Solution:
After the first foreach, add unset ($ V );