Home  >  Article  >  Backend Development  >  The trade-off between php multi-level array foreach reference and copy

The trade-off between php multi-level array foreach reference and copy

WBOY
WBOYOriginal
2016-07-06 13:51:12981browse

<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?

Reply content:

<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?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn