在 PHP 中,我该怎么做:
$test = array(1,2,3,4);
$i=0;
While (!empty($test)) {
//do something with $test[i];
//remove $test[$i];
unset($test[$i]);
}
谢谢
最佳答案
有几种方法可以在遍历数组时修改数组:
您可以使用 array_pop
或 array_shift
,具体取决于您希望元素在其中的顺序
while( $val = array_pop( $arr ) )
-or-
while( $val = array_shift( $arr ) )
这种形式确实有一个问题,它将以任何 虚假值结束 listed in the type comparison table , array()
, false
, ""
, 0
, "0"
, 和 null
值都将结束 while
循环
通常这可以通过
来缓解while( ( $val = array_pop( $arr ) ) !== null )
严格类型比较应该用作 null == false
和其他 falsey 值。同样的问题是,如果数组中的值实际上是 null
遍历数组的一种更安全的方法是测试它是否为空:
while( $arr )
//while( count( $arr ) )
//while( !empty( $arr ) )
{
$val = array_pop( $arr );
//for forward iteration
//$val = array_shift( $arr );
}
empty()
与 if()
检查正好相反。 !empty()
在 while 循环中有一个隐藏的优势,即如果在检查时变量未定义,它会抑制错误。
在 well-written code™ 中这不是问题,但是 well-written code™ 不会在野外自然发生,所以你应该格外小心以防万一。
关于php - 在 php 中迭代数组,但在迭代期间添加到数组/从数组中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7265777/