To remove an existing item from an array, you can use the array_splice()
function.
With array_splice()
, you specify the index (where to start) and the number of items to delete.
Remove the second item.
$cars |
After deletion, the array is automatically reindexed, beginning at index 0.
You can also use the unset()
function to remove existing array items.
Note: The unset() function does not rearrange the indexes, so after deletion, the array will retain the missing indexes. |
Delete the second item.
$cars |
To remove multiple items, the array_splice()
function includes a length parameter that lets you specify how many items to delete.
Remove 2 items, starting from the second item (index 1).
$cars |
The unset()
function accepts an unlimited number of arguments, allowing you to delete multiple array items.
Delete the first and second items.
$cars |
To remove items from an associative array, you can use the unset()
function.
Simply specify the key of the item you wish to delete.
Delete the “model”.
$cars |
You can also use the array_diff() function to remove items from an associative array.
This function returns a new array that excludes the specified items.
Create a new array that excludes “Mustang” and “1964”.
$cars |
Note: The array_diff() function takes values as parameters, not keys. |
The array_pop()
function removes the last item from an array.
Delete the last item.
$cars |
The array_shift()
function removes the first item from an array.
Delete the first item.
$cars |