php高级基础--php在foreach循环后留下数组的引用问题
示例:
<?php
$arr = array(1,2,3,4);
foreach($arr as $key => &$value){
}
foreach($arr as $key => $value){
}
?>
结果:
[1,2,3,3]
解释:
1. foreach不是块级域,数组引用结束,$key , $value 并没有释放内存
2. 当第一次引用循环结束的时候,$value指向数组最后一个元素4
3. 当第二次开始循环 (此时$value 已经是指向最后一个元素,是引用)
循环4次 数组的变化分别是:
1 -> [1,2,3,4]
2 -> [1,2,3,4]
3 -> [1,2,3,3]
第三次value指向最后一个元素3 但是value是全局引用在上次循环指向了最后一个元素 所以value=3的时候 也会把最后一个元素的值改为3
4 -> [1,2,3,3]
注意事项:
1. foreach 实现原理有个内部指针的概念
2. &的foreach循环结束 指针会指向最后一个元素
如何避免:
在用&foreach循环后 unset ($value)
2019-08-01: 今天看到很多人在关注这个问题,关于鸟哥解释的php源码分析的foreach,大家感兴趣的可以去看看:http://www.laruence.com/2008/11/20/630.html
I'm gone to say to my little brother, that he should also visit this blog on regular basis to get updated from most recent gossip.
Hi, I do think this is a great blog. I stumbledupon it ;) I may revisit once again since I book marked it. Money and freedom is the greatest way to change, may you be rich and continue to help others.
yutube
This is a really good tip especially to those fresh to the blogosphere. Short but very precise info… Many thanks for sharing this one. A must read article!
wonderful issues altogether, you just received a emblem new reader. What may you suggest about your submit that you just made a few days ago? Any certain?
Everything is very open with a very clear clarification of the issues. It was definitely informative. Your website is extremely helpful. Many thanks for sharing!
Hi! This is my first comment here so I just wanted to give a quick shout out and say I genuinely enjoy reading your posts. Can you recommend any other blogs/websites/forums that deal with the same subjects? Many thanks!
Thanks , I've recently been searching for info approximately this topic for ages and yours is the best I have came upon till now. However, what in regards to the bottom line? Are you positive about the supply?
Nice post. I learn something new and challenging on sites I stumbleupon on a daily basis. It's always useful to read articles from other writers and practice a little something from other web sites.
I am curious to find out what blog system you are using? I'm experiencing some minor security problems with my latest site and I'd like to find something more secure. Do you have any recommendations?
循环4次 数组的变化分别是: 1-> [1,2,3,1] 2-> [1,2,3,2] 3-> [1,2,3,3] 第三次value指向最后一个元素3 但是value是全局引用在上次循环指向了最后一个元素 所以value=3的时候 也会把最后一个元素的值改为3 4-> [1,2,3,3]