How to delete an element from an PHP Array

How to delete an element from an PHP Array

by cybersal

Removing elements from PHP array

There are multiple was by which we can delete element from a PHP array.

unset()

Code:

$arraylist = [0 => "x", 1 => "y", 2 => "z"];
unset($arraylist[1]);  // Key which you want to delete
          

Output:

[
    [0] => x
    [2] => z
]

Unset doesn’t reset the array keys. In order to reset the array keys we will have to use array_values() after unset function.

array_splice()

Code:

$arraylist = [0 => "x", 1 => "y", 2 => "z"];
 array_splice($arraylist, 1, 1);  //(Array, offset, length)

Output:

[
    [0] => x
    [1] => z
]

It uses array offset and not the keys.

If you use array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to array_values(), which will convert all keys to numerical keys.

Related Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy