Delete an element from an array in PHP

Learn, how to delete an element from an array in PHP? There are 2 ways of deleting an element from the array in PHP which are using unset() and array_splice(). By Abhishek Pathak Last updated : December 20, 2023

Problem statement

Given a PHP array, write PHP code to delete an element from it.

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

PHP - Deleting an Array Element

Arrays store the element together using an index based system, starting from 0. While we can simply set the value to NULL, but it will still be the part of the array and take up space in memory. But using the advanced PHP built-in methods we can easily delete an element from an array. There are 2 ways of deleting an element from the array in PHP which are discussed below.

1. Delete an element from an array using unset() method

The unset() method takes the element which needs to be deleted from the array and deletes it. Note that, when you use unset() the array keys won't re-index, which means there will be no particular index present in that array and if accessed will not return a value. Consider this example,

PHP code to delete an array element unset()

<?php
$array = array(0 => "apple", 1 => "banana", 2 => "carrot");

//unset the second element of array
unset($array[1]);

//Print the array
var_dump ($array);
?>

Output

array(2) {
  [0]=>
  string(5) "apple"
  [2]=>
  string(6) "carrot"
}

Explanation

We define an associative array using the key as the index and unset the second element from it. Now we are left with two elements with no second index between them. If we want to remove as well as shift the elements, we need to use the array_splice method discussed below.

2. Delete an element from an array using array_splice() method

It does the same work as the unset() except that it rearranges and shift the elements to fill the empty space. If you use array_splice() the keys will be automatically reindexed, but the associative keys won't change opposed to array_values() method which will convert all keys to numerical keys.

Also, array_splice() needs the offset as second parameter, which means number of elements to be deleted.

PHP code to delete an array element array_splice

<?php
$array = array(0 => "apple", 1 => "banana", 2 => "carrot");

//Splice the array beginning from 1 index,
//ie second element and delete 1 element.
array_splice($array, 1, 1);

//Print the array
var_dump ($array);
?>

Output

array(2) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "carrot"
}

Explanation

As we can see from output, the array deleted the second element but re-indexed the array thereafter.

If you like the article, share your thoughts below.

PHP Array Programs »

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.