我认为这是不可能的foreach
循环,至少是你写的方式:似乎不仅仅是这样foreach
作品;引用的手册页foreach https://www.php.net/manual/en/control-structures.foreach.php :
Note:除非引用数组,否则 foreach 会在副本上进行操作
指定数组的而不是
数组本身。
**Edit : after thinking a bit about that note, it is actually possible, and here's the solution :**
注释上写着“除非数组被引用" ;这意味着这部分代码应该可以工作:
$i = 0;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
}
请注意&
before $value
.
它实际上显示:
red
blue
white
white
white
white
这意味着添加&
实际上是您正在寻找的解决方案,从内部修改数组foreach
环形 ;-)
**Edit : and here is the solution I proposed before thinking about that note :**
你可以使用while
循环,“手工”做更多的工作;例如 :
$i = 0;
$array = array('red', 'blue');
$value = reset($array);
while ($value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
$value = next($array);
}
会给你这个输出:
red
blue
white
white
white
white