Follow @endyourif rss Facebook LinkedIn

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

Published on Jan 26, 2020

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.

Tags: PHP | splice | unset | array

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP