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

Ser*_*ich 0 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);
Run Code Online (Sandbox Code Playgroud)

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

Don*_*nic 6

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

for ($i = 0; $i < count($current_groups); $i++){
Run Code Online (Sandbox Code Playgroud)

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

你可能会array_filter用来做这个.

$current_groups = array_filter($current_groups, function($x) {
    return $x == 1 || $x == 2;
});
Run Code Online (Sandbox Code Playgroud)

或者array_intersect(感谢@Chris的想法.)

$current_groups = array_intersect($current_groups, [1,2]);
Run Code Online (Sandbox Code Playgroud)