PHP Bug还是我对语言的误解?

前端之家收集整理的这篇文章主要介绍了PHP Bug还是我对语言的误解?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Strange behavior Of foreach2个
> foreach loop and reference of &$value6个
这是我不理解的代码(作为输出).
<?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";
}

?>

输出

First FOREACH
test1
test2
test3
test4

Second FOREACH
test1
test2
test3
test3

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
在第一个foreach语句之后,你有$y指向最后一个数组项:
$x = ['test1','test4'];
$y =& $x[3];

每当您为$y分配一个值时,原始数组都将被修改.

当第二个foreach开始时,在每次迭代时,来自$x的下一个值被放入$y.因此,原始数组将如下所示:

// first iteration
$x = ['test1','test1'];
// second iteration
$x = ['test1','test2'];
// third iteration
$x = ['test1','test3'];
// fourth iteration
$x = ['test1','test3'];
原文链接:https://www.f2er.com/php/135342.html

猜你在找的PHP相关文章