Deleting an element from an array in PHP

D

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:

[code]
unset($array[1])
[/code]

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:

[code]
array_values($array)
[/code]

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:

[code]
array_splice($array, 1, 1)
[/code]

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:

[code]
$array = [0 => “a”, 1 => “b”, 2 => “c”];
$array = array_diff($array, [“a”, “c”]);
[/code]

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.

About the author

By Jamie

My Books