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

WBOY
Release: 2016-07-06 13:51:12
Original
980 people have browsed it

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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?

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template