Deleting an element from an array in PHP Deleting an element from an array in PHP

There are multiple ways to delete an element from array with PHP: unset, array_splice, and array_diff. The splice method is very similar to my article on removing a specific element with JavaScript article.


Using unset to remove an array element

The unset destroys the variable(s) passed into the function. So if you know the element at which to remove you can remove an element with its zero-based index as follows:


unset($array[1])

There is an interesting note here that the indexes of the array are not changed, which leaves a weird result. Let's assume you had three values, after removing the second one your array would longer have a key at index 1, only at 0 and 2. To correct this, you can call:


array_values($array)

Removing an array element with array_splice

The array_splice function is similar, but a little different from unset. It requires two parameters, the first is the position of the starting element to remove and how many elements to remove:


array_splice($array, 1, 1)

This tells PHP to remove one element starting at position one. The second parameter can be higher if you wish to remove multiple elements.

Deleting specific element with array_diff

The array_diff function output is similar to unset where the array is not re-indexed afterwards. However, it offers a nice advantage that you can specify a value(s) to remove when you do not know its index:


$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_diff($array, ["a", "c"]);

The output of $array will only contain "b" at element 1. Again, you would need to call array_values($array) to re-index the values and shifting "b" to be element 0.

Published on Jan 26, 2020

Tags: PHP | splice | unset | Javascript Arrays Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.