Home  >  Article  >  Backend Development  >  引用的疑问

引用的疑问

WBOY
WBOYOriginal
2016-06-20 12:36:37790browse

<?php$arr = ['1', '2', '3', '4'];foreach ($arr as &$i) {}echo implode($arr, ', ')."\n";  //1,2,3,4foreach ($arr as $i) {}echo implode($arr, ', ')."\n";   //1,2,3,3?>
 
打印:
1, 2, 3, 4
 1, 2, 3, 3
在php手册评论中看到的,实在想不明白为什么,求大神解答。


回复讨论(解决方案)

$arr = ['1', '2', '3', '4']; foreach ($arr as &$i) {}echo implode($arr, ', ')."\n";  //1,2,3,4 foreach ($arr as $i) {  echo '*' . join(',', $arr), PHP_EOL;}echo implode($arr, ', ')."\n";   //1,2,3,3
1, 2, 3, 4*1,2,3,1*1,2,3,2*1,2,3,3*1,2,3,31, 2, 3, 3
在笫二个 foreach 中,由于 $i 是 $arr 最后一个元素的引用
所以你可以看到 $arr 在循环中是变化的

所以 foreach ($arr as &$i) {} 后,应 unset($i); 以切断 $arr 的引用

明白了,谢谢

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