算法在PHP中循环无限循环,为什么?

时间:2017-09-07 14:13:28

标签: php for-loop

你能解释一下,代码有什么问题吗?我试图摆脱所有不是1或2的元素......

    $current_groups = [1,2,3,4];
    for ($i = 0; $i < count($current_groups); $i++){
        if ($current_groups[$i]!= 1 and $current_groups[$i] != 2){
            unset($current_groups[$i]);
            $i = $i - 1;
        }
    }
    echo print_r($current_groups, true);

它意外地进入了无限循环......

1 个答案:

答案 0 :(得分:6)

在for循环定义中,$i在每次迭代后递增。

for ($i = 0; $i < count($current_groups); $i++){

然后在身体中$i = $i - 1;,它会回到之前的值。所以,基本上它永远不会改变。

您可以使用array_filter来代替。

$current_groups = array_filter($current_groups, function($x) {
    return $x == 1 || $x == 2;
});

array_intersect(感谢@Chris的想法。)

$current_groups = array_intersect($current_groups, [1,2]);