Q:

Delete an element from an array in PHP

belongs to collection: PHP Array Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

1) Using unset()

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,

Code

<?php

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

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

    //Print the array
    echo $array; // Output: (0 => "apple", 2 => "carrot")

?>

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) Using array_splice()

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() 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.

Code

<?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
    echo $array; // Output: (0 => "apple", 1 => "carrot")

?>

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Create an associative array in PHP... >>
<< How to get the length of the array in PHP?...