Home >Backend Development >PHP Tutorial >php foreach array_merge problems and confusion
Code:
<code>$a = array('a' => array('a')); $b = array('b' => array('b')); foreach ($b as $key => &$item) { $item[] = 'd'; } $a = array_merge($b, $a); $b['b'][] = 'c'; print_r($a); print_r($b);</code>
Result:
<code>Array ( [b] => Array ( [0] => b [1] => d [2] => c ) [a] => Array ( [0] => a ) ) Array ( [b] => Array ( [0] => b [1] => d [2] => c ) )</code>
My confusion is why the operation on $b affects $a after the merger.
Anyone who knows, please clarify, thank you!
Code:
<code>$a = array('a' => array('a')); $b = array('b' => array('b')); foreach ($b as $key => &$item) { $item[] = 'd'; } $a = array_merge($b, $a); $b['b'][] = 'c'; print_r($a); print_r($b);</code>
Result:
<code>Array ( [b] => Array ( [0] => b [1] => d [2] => c ) [a] => Array ( [0] => a ) ) Array ( [b] => Array ( [0] => b [1] => d [2] => c ) )</code>
My confusion is why the operation on $b affects $a after the merger.
Anyone who knows, please clarify, thank you!
Actually, I think you can see it if you change print_r to var_dump
<code>array (size=2) 'b' => & array (size=3) 0 => string 'b' (length=1) 1 => string 'd' (length=1) 2 => string 'c' (length=1) 'a' => array (size=1) 0 => string 'a' (length=1) array (size=1) 'b' => & array (size=3) 0 => string 'b' (length=1) 1 => string 'd' (length=1) 2 => string 'c' (length=1)</code>
Variable b points to a reference type, so if the value of b is changed, the value of b in a will also change
Thank you for the reply from @风咷horn. I googled “php foreach reference” again and found this article, which gave me a better understanding of this issue
[PHP] An interview question about variable reference in foreach loop
Let me tell you my understanding. When using the & symbol, the variables $b and $item will point to an address at the same time. At this time, $b becomes a reference variable. If $item is unset after foreach, this will The reference of $b will be dereferenced.