This article demonstrates how to delete an element from an array in PHP.

1. Using unset() function

There are several options to delete an array element. If you have to delete only a single element from the array, you can use the unset() function.

Download  Run Code

 
Note that the unset() function won’t change the keys of an array, even for numerical arrays. You can call the array_values() function after the unset() function to re-index the keys of numerical arrays.

Download  Run Code

2. Using array_splice() function

Another option to delete elements from the array is using the array_splice() function. It removes a specified portion of the array and optionally replaces it with elements of the replacement array. It should be noted that the array_splice() method automatically re-indexes the keys in numerical arrays. For example, the following code removes a single array element at position 1 and normalizes array keys.

Download  Run Code

 
The following example removes three consecutive elements from the array, starting at position 1.

Download  Run Code

3. Using array_diff() function

The array_diff() function is commonly used to filter the array elements by their value. It computes the difference between two arrays and returns all values in the first array that are not present in the second array.

Download  Run Code

 
The following solution removes the elements whose values are mango or banana from the fruits array. Note that array_diff() function returns a new array and does not re-index the keys.

Download  Run Code

4. Using array_diff_key() function

The array_diff_key() function is similar to the array_diff() function, except the comparison is done on the keys instead of the values. As with array_diff, array_diff_key() returns a new array and doesn’t re-index the array keys. The following code demonstrates this:

Download  Run Code

 
If you have a numeric array of keys you want to remove, you can flip it with array_flip() before passing to the array_diff_key() function.

Download  Run Code

5. Using array_filter() function

You might want to conditionally remove elements from an array that satisfies a predicate. This can be achieved with the array_filter() function, which accepts a callback function. The default argument to the callback function is an array value. You can pass the flag ARRAY_FILTER_USE_KEY to have the key passed to the callback instead of the value, as illustrated below:

Download  Run Code

 
Alternatively, you can use the ARRAY_FILTER_USE_BOTH flag to have both value and key passed as arguments to the callback function.

Download  Run Code

That’s all about deleting an element from an array in PHP.