HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Remove/Delete Array Items

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:


<!DOCTYPE html>
<html>
<body>
<pre>

<?php  
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);
var_dump($cars);
?>  

</pre>
</body>
</html>



Output

array(2) {
[0]=>
string(5) "Volvo"
[2]=>
string(6) "Toyota"
}

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

<!DOCTYPE html>
<html>
<body>
<pre>

<?php  
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[0], $cars[1]);
var_dump($cars);
?>  

</pre>
</body>
</html>

Output

array(1) {
[2]=>
string(6) "Toyota"
}

• 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":

<!DOCTYPE html>
<html>
<body>
<pre>

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

</pre>
</body>
</html>

Output

array(2) {
["brand"]=>
string(4) "Ford"
["year"]=>
int(1964)
}