在PHP中,算法以for循环进入无限循环,为什么?

在PHP中,算法以for循环进入无限循环,为什么?,php,for-loop,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

你能解释一下代码有什么问题吗?我试图去除所有不是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);
$current_group=[1,2,3,4];
对于($i=0;$i

它意外地进入无限循环…

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

for ($i = 0; $i < count($current_groups); $i++){
或者
array\u intersect
(感谢@Chris的创意。)


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

for ($i = 0; $i < count($current_groups); $i++){
或者
array\u intersect
(感谢@Chris的创意。)


非常感谢您提供的解决方案,我一定会使用它。但是根据我的代码,我认为当数组中没有3和4时,循环将增加$I变量直到数组的大小并停止,不是吗?@不要惊慌
array\u diff()
不会比
array\u filter()更简单?(只是一个理论问题,未经测试)
$current_groups=array_diff($current_groups[1,2])
@SergeyVladimirovich循环确实增加了
$i
变量。但是当你使用
$i=$i-1在循环中,它否定了这一点。@Chris好主意!我认为我们的目标是保持1和2的价值观,同时去掉其他的价值观
array\u intersect
可以做到这一点。@Don't别怪我,你说得对;)我第一次读的时候就明白了相反的意思。非常感谢你提供的解决方案,我一定会使用它。但是根据我的代码,我认为当数组中没有3和4时,循环将增加$I变量直到数组的大小并停止,不是吗?@不要惊慌
array\u diff()
不会比
array\u filter()更简单?(只是一个理论问题,未经测试)
$current_groups=array_diff($current_groups[1,2])
@SergeyVladimirovich循环确实增加了
$i
变量。但是当你使用
$i=$i-1在循环中,它否定了这一点。@Chris好主意!我认为我们的目标是保持1和2的价值观,同时去掉其他的价值观
array\u intersect
可以做到这一点。@Don't别怪我,你说得对;)我第一次阅读时就明白了相反的意思。
$current_groups = array_intersect($current_groups, [1,2]);