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?
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 useunset()
and reindex your array after it witharray_values()
. Also if you just want to filter out 10 and 5 usearray_filter()
– Quetzalcoatl$i==10
a single=
is assigning a value and not testing a value – Truckage