这是我不理解的代码(作为输出).
<?php
$x = ['test1', 'test2', 'test3', 'test4'];
echo "First FOREACH\n";
foreach ($x as &$y)
{
echo $y."\n";
}
echo "\n\nSecond FOREACH\n";
foreach ($x as $y)
{
echo $y."\n";
}
?>
Run Code Online (Sandbox Code Playgroud)
输出:
First FOREACH
test1
test2
test3
test4
Second FOREACH
test1
test2
test3
test3
Run Code Online (Sandbox Code Playgroud)
PS:我正在运行它:
php -v
PHP 5.6.11-1ubuntu3.1 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
Run Code Online (Sandbox Code Playgroud)
它更像是一个功能,它在foreach联机帮助页中有记录
警告 即使在foreach循环之后,$ value和最后一个数组元素的引用仍然存在.建议通过unset()销毁它.
手册页上有一些相关的评论,这里有一个 http://php.net/manual/en/control-structures.foreach.php#111688
有关如何发生这种情况的更多信息http://schlueters.de/blog/archives/141-References-and-foreach.html
在第一个foreach语句之后,您$y指向最后一个数组项:
$x = ['test1', 'test2', 'test3', 'test4'];
$y =& $x[3];
Run Code Online (Sandbox Code Playgroud)
每当您为$y原始数组赋值时都会被修改.
当第二的foreach开始,在每次迭代下一个值从$x投入$y.因此,在每次迭代时,原始数组将如下所示:
// first iteration
$x = ['test1', 'test2', 'test3', 'test1'];
// second iteration
$x = ['test1', 'test2', 'test3', 'test2'];
// third iteration
$x = ['test1', 'test2', 'test3', 'test3'];
// fourth iteration
$x = ['test1', 'test2', 'test3', 'test3'];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |