Home > Backend Development > PHP Tutorial > 引用的疑问

引用的疑问

WBOY
Release: 2016-06-20 12:36:37
Original
842 people have browsed it

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

打印:
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
Copy after login
1, 2, 3, 4*1,2,3,1*1,2,3,2*1,2,3,3*1,2,3,31, 2, 3, 3
Copy after login
在笫二个 foreach 中,由于 $i 是 $arr 最后一个元素的引用
所以你可以看到 $arr 在循环中是变化的

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

明白了,谢谢

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