W3docs

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.

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:

Example of removing an element from an array using a for loop in PHP

<?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 )

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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:

Example of using array_values() function to reset the keys of an array in PHP

<?php

$numbers = [1, 2, 3, 4, 5];
$numbers = array_values($numbers);
print_r($numbers); // Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 )