array_splice() isn't working properly inside a loop
Asked Answered
P

1

5

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?

Partizan answered 17/12, 2015 at 12:12 Comment(6)
If you use array_splice() like this it will remove the array element AND reindexed the array. So if you remove 5 with the key 0 you will then go to 1 with your loop, but the array gets reindexed to: [0 => 10, 1 => 6] and you skip 10, because you don't go back to 0. So just use unset() and reindex your array after it with array_values(). Also if you just want to filter out 10 and 5 use array_filter()Quetzalcoatl
it seems a infinite loop?Renteria
For loop is incorrectly stated. Use $i==10 a single = is assigning a value and not testing a valueTruckage
sorry guys, i've updated my code. done the example code in a rush.Partizan
Can you please explain what you're trying to achieve?Baltimore
if supposed 2 elements on the array were true for the if statement it should return the message. but then the same time removes it from the array with re-indexing. it works well if one element was true, but if its more than it, then it doesn't work at all.Partizan
S
13

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>
    }
}
She answered 17/12, 2015 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.