Home » PHP

Delete an element from an array in PHP

In this article, we will 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().
Submitted by Abhishek Pathak, on November 05, 2017

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) 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,



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

    //unset the second element of array

    //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.



    $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.

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.