Skip to content
Advertisement

array_splice() isn’t working properly inside a loop

This code works as expected and removes the array element when the value is either 5 or 10. But it only works when I have 1 value which is 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 other elements in the array.

My code:

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 is as expected: [3, 4]. But if I have an array like: [3, 5, 10, 4] it just removes the 5, but not the 10: [3, 10, 4].

I can’t seem to find it what I’m doing wrong and why my code doesn’t work as expected?

Advertisement

Answer

You seem to miss that the array-elements are renumbered after the splice-operation.

You would have to adjust the loop-variable:

for($i = 0; $i &lt; sizeof($somevar); $i++) {
    if($somevar[$i] == 5 || $somevar[$i] == 10) {
        echo 'the sumvar'.$somevar[$i].' exists&lt;br>';
        array_splice($somevar, $i, 1);
        <b>$i--;</b>
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement