How to remove an element from an array
Short answer
unset() removes an element by key. To make the keys sequential again, pass the array through array_values():
<?php
$colors = ['red', 'green', 'blue'];
unset($colors[1]);
print_r(array_values($colors));Output:
Array
(
[0] => red
[1] => blue
)By value
If you do not know the key, filter the array with array_filter():
<?php
$colors = ['red', 'green', 'blue'];
$colors = array_values(array_filter($colors, fn ($color) => $color !== 'green'));
echo implode(', ', $colors);Output:
red, blueThe first or the last element
array_shift() removes the first element, array_pop() the last:
<?php
$numbers = [1, 2, 3, 4];
array_shift($numbers);
array_pop($numbers);
echo implode(', ', $numbers);Output:
2, 3Functions used in this recipe
- array_filter — Keeps the array elements that pass a test.
- array_search — Searches an array for a value and returns its key.
- array_pop — Removes the last element of an array and returns it.