如何遍历在迭代时增长的数组中的 *所有* 值?

How do I iterate over *all* values in an array that grows while iterating?

下面的示例将不起作用,因为 foreach 适用于数组的副本,但它从概念上展示了我想要实现的目标。

$items = array('a', 'b', 'c', 'd');
foreach ($items as $i) {
  echo $i;
  if ($i === 'c') {
    $items[] = 'e';
  }
}

我希望它打印“abcde”,但由于上述原因,它只打印“abcd”。我查看了 array_maparray_walk 以及其他人,但没有找到解决方案。

您可以使用 while 循环(或者也可能是普通的 for 循环),它会在每次迭代后评估退出条件。请注意,在此代码中,$i 已更改为索引,因此您使用 $items[$i] 获取实际字符。

$items = array('a', 'b', 'c', 'd');
$i = 0;
while ($i < count($items)) {
  echo $items[$i];
  if ($items[$i] === 'c') {
    $items[] = 'e';
  }
  $i++;
}

另一种使用 while 的变体,无需计数。也适用于关联数组并在需要时检索 $k 中的键:

while(list($k, $i) = each($items)) {
  echo $i;
  if ($i === 'c') {
    $items[] = 'e';
  }
}

或使用 for 循环,但这将在包含布尔值 false 或计算结果为 false:

的任何元素处停止
for($i = reset($items) ; $i ; $i = next($items)) {