PHP Delete Array Items


Remove Array Item

To remove an existing item from an array, you can use the unset() function.

The unset() function deletes specified variables, and can therefor be used to delete array items:

Example

Remove the second item:

$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);
Try it Yourself »

Remove Multiple Array Items

The unset() function takes a unlimited number of arguments, and can therefor 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]);
Try it Yourself »

Note: The unset() function will NOT re-arrange the indexes, and the examples above will no longer contain the missing indexes.


Using the array_splice Function

If you want the array to re-arrange the indexes, you can use the array_splice() function.

With the array_splice() function you specify the index (where to start) and how many items you want to delete.

Example

Remove the second item:

$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);
Try it Yourself »

After the deletion, the array gets reindexed automtically, starting at index 0.


Remove Item From an Associative Array

To remove items from an associative array, you can use unset() function like before, but referring to the key name instead of index.

Example

Remove the "model":

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
unset($cars["model"]);
Try it Yourself »

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.