Table of Contents
To remove an existing item from an array, 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.
<h4>Remove_Array_Item</h4>
<p>Remove the ... item:</p>
<pre>
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);
var_dump($cars);
?>
</pre>
Result View Example
You can also use the unset() function to delete existing array items.
<h4>Using_the_unset_Function</h4>
<p>Remove the second item:</p>
<pre>
<?php
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);
var_dump($cars);
?>
</pre>
Result View Example
To remove multiple items, the array_splice() function takes a length parameter that allows you to specify the number of items to delete.
<h4>Remove_Multiple_Array_Items</h4>
<p>Remove 2 items, starting a the second item (index 1):</p>
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 2);
var_dump($cars);
?>
Result View Example
The unset() function takes a unlimited number of arguments, and can therefore be used to delete multiple array items:
<h4>Remove_the_first_and_the_second_item</h4>
<p>Remove the first and the second item:</p>
<pre>
<?php
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[0], $cars[1]);
var_dump($cars);
?>
</pre>
Result View Example
To remove items from an associative array, you can use the unset() function.
Specify the key of the item you want to delete.
<h4>Remove_Item_From_an_Associative_Array</h4>
<p>Remove the "model":</p>
<pre>
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
unset($cars["model"]);
var_dump($cars);
?>
</pre>
Result View Example
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.
<h4>Using_the_array_diff_Function</h4>
<p>Create a new array, without "Mustang" and "1964":</p>
<pre>
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$newarray = array_diff($cars, ["Mustang", 1964]);
var_dump($newarray);
?>
</pre>
Result View Example
The array_pop() function removes the last item of an array.
<h4>Remove_the_Last_Item</h4>
<p>Remove the last item:</p>
<pre>
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_pop($cars);
var_dump($cars);
?>
</pre>
Result View Example
The array_shift() function removes the first item of an array.
<h4>Remove_the_First_Item</h4>
<p>Remove the first item:</p>
<pre>
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_shift($cars);
var_dump($cars);
?>
</pre>
Result View Example
Document in project
You can Download PDF file.