How do you remove an array element in a foreach loop?
It is generally not recommended to remove array elements while iterating over the array using a foreach loop, because the loop will behave unexpectedly when elements are removed. Instead, you can use a regular for
loop and use the unset
function to remove the element.
Here is an example of how you can remove an element from an array using a for
loop:
<?php
$numbers = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($numbers); $i++) {
if ($numbers[$i] == 3) {
unset($numbers[$i]);
}
}
print_r($numbers); // Array ( [0] => 1 [1] => 2 [3] => 4 [4] => 5 )
Watch a video course
Learn object oriented PHP
Note that the above example will leave a "gap" in the array where the element was removed, so the keys of the elements will not be contiguous. To fix this, you can use the array_values
function to reset the keys of the array:
<?php
$numbers = [1, 2, 3, 4, 5];
$numbers = array_values($numbers);
print_r($numbers); // Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 )