How to Delete an Element from an Array in PHP

Created
Modified

Using unset Function

The unset(mixed $var, mixed ...$vars): void function destroys the specified variables. For example,

$arr = ["a", "b", "d"];

unset($arr[1]);
print_r($arr);
Array
(
  [0] => a
  [2] => d
)

Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0.

Using array_splice Function

The array_splice(): array function removes a portion of the array and replace it with something else.

$arr = ["a", "b", "d"];

array_splice($arr, 1, 1);
print_r($arr);
Array
(
  [0] => a
  [1] => d
)

Using array_filter Function

If you want to delete all elements with a specific value in the array you can use array_filter().

See the following example:

$arr = ["a", "b", "d", "b"];

$arr = array_filter($arr, function($ele){
  return $ele !== "b";
});
print_r($arr);
Array
(
  [0] => a
  [2] => d
)

Related Tags