1. <?php
  2. $arr = array(1,2,3,4);
  3. foreach($arr as $key => &$value){
  4. }
  5. foreach($arr as $key => $value){
  6. }
  7. ?>


  1. [1,2,3,3]


  1. 1. foreach不是块级域,数组引用结束,$key , $value 并没有释放内存
  2. 2. 当第一次引用循环结束的时候,$value指向数组最后一个元素4
  3. 3. 当第二次开始循环 (此时$value 已经是指向最后一个元素,是引用)
  4. 循环4 数组的变化分别是:
  5. 1 -> [1,2,3,4]
  6. 2 -> [1,2,3,4]
  7. 3 -> [1,2,3,3]
第三次value指向最后一个元素3 但是value是全局引用在上次循环指向了最后一个元素 所以value=3的时候 也会把最后一个元素的值改为3
  1. 4 -> [1,2,3,3]


  1. 1. foreach 实现原理有个内部指针的概念
  2. 2. &的foreach循环结束 指针会指向最后一个元素

在用&foreach循环后 unset ($value)

2019-08-01: 今天看到很多人在关注这个问题,关于鸟哥解释的php源码分析的foreach,大家感兴趣的可以去看看:

点赞 ( 5 )

12 条评论

  1. coupon

    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.

  2. tracfone special coupon 2022

    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.

  3. yutube


  4. Filomena

    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!

  5. pop over to these guys

    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?

  6. Bocaidama

    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!

  7. Dnfsfu

    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!

  8. arveles

    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?

  9. 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.

  10. instagram takipçi satın al

    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?

  11. kevinfei

    循环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]