Removing a element from an array

To remove an element from an array, we use array_splice().

$arr = array("red", "green", "blue", "black");
print_r($arr);
for ($i = 0; $i < count($arr); $i++) {
  if ($i == 2) {
    array_splice($arr, $i, 1);
  }
}
print_r($arr);

The element blue has been removed from the array.

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => black
)
Array
(
    [0] => red
    [1] => green
    [2] => black
)

Caution about using array_splice() in a loop

$arr = array("red", "green", "blue", "black");
print_r($arr);
for ($i = 0; $i < count($arr); $i++) {
  print $arr[$i] . ' ';
  if ($arr[$i] === "blue") {
    array_splice($arr, $i, 1); $i--;
  }
  print $arr[$i] . "\n"; 
}
print_r($arr);

Output

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => black
)
red red
green green
blue green
black black
Array
(
    [0] => red
    [1] => green
    [2] => black
)

The moment we remove an element with an array_splice, the next element becomes the current element. If we continue looping, we would skip the next element. The solution is to decrement the index by one, making previous element the current element. Accessing the current element at this point would mean accessing the previous element. Thus decrement must be followed by continue statement as follows:

$arr = array("red", "green", "blue", "black");
print_r($arr);
for ($i = 0; $i < count($arr); $i++) {
  print $arr[$i] . ' ';
  if ($arr[$i] === "blue") {
    array_splice($arr, $i, 1); 
    $i--;
    print "\n";
    continue;
  }
  print $arr[$i] . "\n"; 
}
print_r($arr);