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);
Results:
Array( [b] => Array ( [0] => b [1] => d [2] => c ) [a] => Array ( [0] => a ))Array( [b] => Array ( [0] => b [1] => d [2] => c ))
My confusion is why after the merger, the operation on $b affects $ A.
Know the great God, please excuse me, thank you!
Reply content:
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);
Results:
Array( [b] => Array ( [0] => b [1] => d [2] => c ) [a] => Array ( [0] => a ))Array( [b] => Array ( [0] => b [1] => d [2] => c ))
My confusion is why after the merger, the operation on $b affects $ A.
Know the great God, please excuse me, thank you!
Actually, I feel like you changed the Print_r into a var_dump, you can see it.
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)
Variable b points to a reference type, so the value of B is changed, and the value of B in a changes with
Thank you for the sound of the Horn's reply, I again Google "php foreach reference", found this article, better understand the problem
A side question for a variable reference in the "PHP" Foreach Loop
I say I understand that when using the & symbol, the variable $b and the $item will point to an address at the same time, $b becomes a reference variable, if after foreach, unset drop $item, this time will be lifted $b reference.