Array_splice () does not work properly inside the loop

This code works as expected and removes the element of the array when the value is 5 or 10. But it only works when I have 1 value equal to 5 or 10 in the array.

If I have more than 1 value, which is 5 or 10, it removes only 1 of them and leaves the rest of the elements in the array.

My code is:

for($i = 0; $i <= 10; $i++) {
    if($somevar[$i] == 5 || $somevar[$i] == 10) {
        echo 'the sumvar'.$somevar[$i].' exists<br>';
        array_splice($somevar, $i, 1);
    }
}

As an example, if I have: [3, 5, 4]the result will be as expected: [3, 4]. But if I have an array like this: [3, 5, 10, 4]he simply removes 5 but not 10: [3, 10, 4].

I cannot find what I am doing wrong, and why is my code not working as expected?

+4
source share
1

, , -.

:

for($i = 0; $i < sizeof($somevar); $i++) {
    if($somevar[$i] == 5 || $somevar[$i] == 10) {
        echo 'the sumvar'.$somevar[$i].' exists<br>';
        array_splice($somevar, $i, 1);
        $i--;
    }
}
+7

Source: https://habr.com/ru/post/1620544/


All Articles