在下面我将尝试精确解释迭代在不同情况下的工作原理。 我不知道为什么 将元素添加到数组迭代在foreach语句中php
$arr=[1,2,3];
$count=0;
foreach ($arr as $value){ \\
echo "$value\n";
if ($count++<10) $arr[]=$value+1; \\add new element
}
print_r($arr);
结果
1
2
3
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 2
[4] => 3
[5] => 4
)
而
$arr=[1,2,3];
$count=0;
foreach ($arr as &$value){ \\reference elemnt
echo "$value\n";
if ($count++<10) $arr[]=$value+1;
}
print_r($arr);
结果
1
2
3
2
3
4
3
4
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 2
[4] => 3
[5] => 4
[6] => 3
[7] => 4
)
或更好的问题是什么的foreach机制在PHP 感谢
请问任何人都可以告诉我什么是在引擎盖下运行这些代码。 – Bagheri
@Bagheri PHP是开源的,用C编写。如果你认为你可以处理它,那么你可以[查看源代码](https://github.com/php/php-src)。我无法帮助你。 – apokryfos