PHP Basic Tutorial
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.
array_splice()
:This function removes a portion of the array and can optionally replace it with new elements.
Try it yourself
unset()
to Remove an Element by Key:This is the simplest way to remove an element by specifying its key or index.
Try it yourself
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:
Try it yourself
You can also use unset()
to remove elements by their keys in an associative array.
Try it yourself
array_diff()
to Remove Specific Values:You can remove specific values by creating a difference between arrays.
Try it yourself
You can also use the array_diff()
function to remove items from an associative array.
Try it yourself
Note
array_diff()
works based on values, and it is case-sensitive.
array_pop()
removes the last element of the array.
Try it yourself
array_shift()
removes the first element of the array.
Try it yourself