Advertisement
Google Ad Slot: content-top
PHP Remove Array Items
To remove items from an array in PHP, you can use various methods based on your requirements, whether you want to remove a value by its key, unset specific elements, or filter elements out conditionally.
Using array_splice():
This function removes a portion of the array and can optionally replace it with new elements.
Using unset() to Remove an Element by Key:
This is the simplest way to remove an element by specifying its key or index.
Note
unset() removes the element but does not reindex numeric keys. If you want to reindex the array, use array_values().
The unset() function takes a unlimited number of arguments, and can therefore be used to delete multiple array items:
Remove Item From an Associative Array
You can also use unset() to remove elements by their keys in an associative array.
Using array_diff() to Remove Specific Values:
You can remove specific values by creating a difference between arrays.
You can also use the array_diff() function to remove items from an associative array.
Note
array_diff() works based on values, and it is case-sensitive.
Remove the Last Item
array_pop() removes the last element of the array.
Remove the First Item
array_shift() removes the first element of the array.