There are many easy ways to delete an array element. Some functions are different and more useful in the specific problem than others. The ancient way is such as using foreach ($arrray), check every element one by one if match then we remove it from an array. In PHP we have a bunch of functions that can help us remove one or multiple element from array.
A. Remove One Element From Array
We have two methods here if we just want to delete one array element.
1. array_splice() method
array_splice method needs the offset as a second parameter, not the key. If An array element had been removed the keys will be automatically re-indexed.We have two methods here if we just want to delete one array element.
array_splice ( array &$input , int $offset [, int $length = count($input);
Look closely all the keys have been converted starting from zero.
Unlike array_splice, unset() method will not re-index keys so they won’t change after you remove an element. And we are not using offset instead of an actual key from the element we want to delete.
If you want to convert all keys to be re-indexed like array_splice. You can use array_values() after unset() that will reset all keys to numerical enumerated keys from zero.
B. Remove Multiple Array Elements
unset() and array_splice() are a great tool but you don’t want use those to remove multiple elements from an array. Depending on what you know, you can use array_diff() and array_diff_key(). Both functions can remove multiple elements depending on what the values or the keys you have already known.
1. array_diff() method
You can use array_diff() if you already know the values of the elements which you want to remove. This function compares the input array against one or more other arrays. It won’t re-index the keys of the array.
array_diff ( array $array1 , array $array2 [, array $… ] )
If you don’t care about the values of the elements but you want to just remove from the keys, we can use array_diff_key(). This function compares the keys from array1 against the keys from array2 and then returns the difference. That means it will ignore the values and won’t re-index the keys of the array.
array_diff_key ( array $array1 , array $array2 [, array $… ] )