Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Remove Array Item

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.

Example

Remove the second item.

$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);

After deletion, the array is automatically reindexed, beginning at index 0.

Using the unset Function

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.

Example

Delete the second item.

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

Remove Multiple Array Items

To remove multiple items, the array_splice() function includes a length parameter that lets you specify how many items to delete.

Example

Remove 2 items, starting from the second item (index 1).

$cars = array("Volvo", "BMW", "Toyota");
rray_splice($cars, 1, 2);

The unset() function accepts an unlimited number of arguments, allowing you to delete multiple array items.

Example

Delete the first and second items.

$cars = array("Volvo", "BMW", "Toyota");
unset($cars[0], $cars[1]);

 

Remove Item From an Associative Array

To remove items from an associative array, you can use the unset() function.

Simply specify the key of the item you wish to delete.

Example

Delete the “model”.

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

 

Using the array_diff Function

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.

Example

Create a new array that excludes “Mustang” and “1964”.

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$newarray = array_diff($cars, ["Mustang", 1964]);
Note: The array_diff() function takes values as parameters, not keys.

Remove the Last Item

The array_pop() function removes the last item from an array.

Example

Delete the last item.

$cars = array("Volvo", "BMW", "Toyota");
array_pop($cars);

Remove the First Item

The array_shift() function removes the first item from an array.

Example

Delete the first item.

$cars = array("Volvo", "BMW", "Toyota");
array_shift($cars);