PHP Remove Array Items
In PHP, you can remove/delete array items with several different functions:
array_splice()- removes a portion of the array starting from a start position and lengthunset()- removes the element associated with a specific keyarray_diff()- remove items from an associative arrayarray_pop()- removes the last array itemarray_shift()- removes the first array item
PHP array_splice() Function
With the array_splice() function you specify the index (where to start) and how many items you want to delete.
After the deletion, the array gets re-indexed automatically, starting at index 0.
Example
Remove the second item:
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);
var_dump($cars);
Remove Multiple Array Items
To remove multiple items, the array_splice() function takes a length parameter that allows you to specify the number of items to delete.
Example
Remove 2 items, starting a the second item (index 1):
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 2);
var_dump($cars);
PHP unset() Function
You can also use the unset() function to delete existing array items.
Note: The
unset()function does not re-index the array. So, if you remove an element at index 1, the other elements (e.g., at index 0, 2, 3, etc.) will keep their original indices, leading to a "gap " in the sequence of indices.
Example
Remove the second item:
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);
var_dump($cars);
Remove Multiple Array Items
The unset() function takes a unlimited number of arguments, and can therefore be used to delete multiple array items:
Example
Remove the first and the second item:
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[0], $cars[1]);
var_dump($cars);
Remove Item From an Associative Array
To remove items from an associative array, you can use the unset() function.
Specify the key of the item you want to delete.
Example
Remove the "model":
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
unset($cars["model"]);
var_dump($cars);
PHP array_diff() Function
You can also use the array_diff() function to remove items from an associative array.
This function returns a new array, without the specified items.
Example
Create a new array, without "Mustang" and "1964":
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$newarray = array_diff($cars, ["Mustang", 1964]);
var_dump($newarray);
Note: The
array_diff()function takes valuesas parameters, and not keys.
PHP array_pop() - Remove Last Array Item
The array_pop() function removes the last item of an array.
Example
Remove the last item:
$cars = array("Volvo", "BMW", "Toyota");
array_pop($cars);
var_dump($cars);
PHP array_shift() - Remove First Array Item
The array_shift() function removes the first item of an array.
Example
Remove the first item:
$cars = array("Volvo", "BMW", "Toyota");
array_shift($cars);
var_dump($cars);