Skip to main content

Deleting array elements by value in PHP

Consider an array foo with multiple values, and consider the problem of deleting an element from the array, given just the value. Let the variable $delValue hold the value to be  found and deleted.

Using array_search and unset

The strict operator !== is required because the array_search function returns the key of the value in the array, if present. Since the key can be 0 and 0 evaluates to false in PHP, a strict comparison is required.
The method doesn’t work for multiple entries of the value, but with a slight modification, it can be made to :

Using array_diff

This method only works for arrays whose members can be converted to strings.

$foo = array_diff($foo, [$delValue]);

delValue is cast into an array, and array_diff returns only the values of foo that will not be found in [$delValue]. Thus, all instances of delValue are deleted. This is a concise, powerful way that successfully deletes multiple entries of delValue.

Using array_keys

This is similar to the first method, but multiple entries can be successfully deleted.

 

The argument $delValue tells the function array_keys to return keys only for the values *equal to* delValue, and the third argument true signifies that strict comparison (===) be used for checking the values.

Using Anonymous Functions with array_filter

A neat method that only works for versions of PHP >= 5.3.0.

The anonymous function returns a boolean value, which determines whether an element should pass through the filter or not. All values of the array foo *strictly not equal to* delValue pass through and become a part of the new array. Worth noting that multiple instances of delValue are deleted.

Using array_flip

The function flips keys and values of the array passed as an argument. In the case of multiple values, only the latest key is used; the rest are discarded. Also, it’s necessary that the values be either integers or strings or be convertible as such.

Multiple values are deleted as a side-effect of the array_flip call, although some data loss can possibly occur.

Using comparisons and loops

Since each element is looped over, multiple values if present are all deleted.

Using array_splice

The function array_splice can also be used to delete values from an array.

The method only deletes one instance of the value from the array. In the case of associative arrays or arrays in which keys have gaps, the method fails.

References

  1. array_search
  2. unset
  3. array_diff
  4. array_keys
  5. array_flip
  6. array_filter
  7. Anonymous Functions
  8. array_splice

Leave a Reply

Your email address will not be published. Required fields are marked *