Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 853
CudoX Avatar asked Dec 17 '15 12:12

CudoX


People also ask

What is array_ splice in Php?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).

What is splice in javascript?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

What is the function to delete an element of an array in PHP?

Answer: Use the PHP unset() Function If you want to delete an element from an array you can simply use the unset() function.


1 Answers

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>
    }
}
like image 89
Ctx Avatar answered Sep 28 '22 03:09

Ctx