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?
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).
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
Answer: Use the PHP unset() Function If you want to delete an element from an array you can simply use the unset() function.
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 < sizeof($somevar); $i++) {
if($somevar[$i] == 5 || $somevar[$i] == 10) {
echo 'the sumvar'.$somevar[$i].' exists<br>';
array_splice($somevar, $i, 1);
<b>$i--;</b>
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With