$a=[1,2,3]; foreach ($a as &$v){} foreach ($a as $v){} var_dump ($a) 等于多少; php

$a=[1,2,3]; foreach ($a as &$v){} foreach ($a as $v){} var_dump ($a) 等于多少;
答案:122

​ 解析:

$value即使在foreach循环之后 , a和最后一个数组元素的引用仍然存在。建议通过unset()销毁它。否则,您将遇到以下行为:
參考資料
http://php.net/manual/en/control-structure...

在 Warning 中有明確指出此問題。


image

http://php.net/manual/en/language.references.whatdo.php

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value.

在赋值数组的时候,如果=右边的数据存在引用,那边赋值的新数组对应的元素也是引用,所以改变$c[0]的值 也会同时改变$a[0]的值。

参考:
https://www.php.net/manual/en/control-structures.foreach.php

https://www.cnblogs.com/xfych/p/14927049.html

https://www.php.net/manual/en/language.references.whatdo.php

https://blog.csdn.net/ohmygirl/article/details/8726865

https://segmentfault.com/q/1010000002477319

https://www.php.net/manual/en/features.gc.refcounting-basics.php

posted @ 2021-06-24 15:21  这该死的代码  阅读(112)  评论(0编辑  收藏  举报