Advertisement

Google Ad Slot: content-top

PHP Remove Array Items

~1 min read · PHP
On this page

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.

Example
Try it yourself

Using unset() to Remove an Element by Key:


This is the simplest way to remove an element by specifying its key or index.

Example
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:

Example
Try it yourself

Remove Item From an Associative Array


You can also use unset() to remove elements by their keys in an associative array.

Example
"John", "age" => 30, "gender" => "male"]; unset($person["age"]); // Removes "age" print_r($person); // Output: ["name" => "John", "gender" => "male"] ?>
Try it yourself

Using array_diff() to Remove Specific Values:


You can remove specific values by creating a difference between arrays.

Example
Try it yourself

You can also use the array_diff() function to remove items from an associative array.

Example
"John", "age" => 30, "gender" => "male", "country" => "USA" ]; // Remove "male" and "USA" $result = array_diff($person, ["male", "USA"]); print_r($result); ?>
Try it yourself

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.

Example
Try it yourself

Remove the First Item


array_shift() removes the first element of the array.

Example
Try it yourself