Home > Article > Backend Development > The trade-off between php multi-level array foreach reference and copy
<code>$a = [ "a"=>["cc"=>11] , "b"=>["cc"=>22] ]; echo "\n".$a['a']["cc"].",".$a['b']["cc"]; $i=1; //(1)拷贝,$a无变化 foreach($a as $k=>$v) { $v['cc']=$i; $i+=1; } echo "\n".$a['a']["cc"].",".$a['b']["cc"]; //(2)引用 foreach($a as $k=>&$v) { $v['cc']=$i; $i+=1; } echo "\n".$a['a']["cc"].",".$a['b']["cc"]; //(3)拷贝 foreach($a as $k=>$v) { $a[$k]["cc"]=$i; $i+=1; } echo "\n".$a['a']["cc"].",".$a['b']["cc"]; </code>
The default foreach copies the array, which requires twice the memory. Will the performance be very low? Why is it designed this way?
If the array is very large, would it be better to use a reference? What are the advantages and disadvantages of each?
<code>$a = [ "a"=>["cc"=>11] , "b"=>["cc"=>22] ]; echo "\n".$a['a']["cc"].",".$a['b']["cc"]; $i=1; //(1)拷贝,$a无变化 foreach($a as $k=>$v) { $v['cc']=$i; $i+=1; } echo "\n".$a['a']["cc"].",".$a['b']["cc"]; //(2)引用 foreach($a as $k=>&$v) { $v['cc']=$i; $i+=1; } echo "\n".$a['a']["cc"].",".$a['b']["cc"]; //(3)拷贝 foreach($a as $k=>$v) { $a[$k]["cc"]=$i; $i+=1; } echo "\n".$a['a']["cc"].",".$a['b']["cc"]; </code>
The default foreach copies the array, which requires twice the memory. Will the performance be very low? Why is it designed this way?
If the array is very large, would it be better to use a reference? What are the advantages and disadvantages of each?