PHP array delete by value (not key)

ID : 1362

viewed : 208

Tags : phparraysphp





Top 5 Answer for PHP array delete by value (not key)

vote vote

95

Using array_search() and unset, try the following:

if (($key = array_search($del_val, $messages)) !== false) {     unset($messages[$key]); } 

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

vote vote

84

Well, deleting an element from array is basically just set difference with one element.

array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3] 

It generalizes nicely, you can remove as many elements as you like at the same time, if you want.

Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.

vote vote

78

One interesting way is by using array_keys():

foreach (array_keys($messages, 401, true) as $key) {     unset($messages[$key]); } 

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).

This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4]).

vote vote

68

If you know for definite that your array will contain only one element with that value, you can do

$key = array_search($del_val, $array); if (false !== $key) {     unset($array[$key]); } 

If, however, your value might occur more than once in your array, you could do this

$array = array_filter($array, function($e) use ($del_val) {     return ($e !== $del_val); }); 

Note: The second option only works for PHP5.3+ with Closures

vote vote

51

$fields = array_flip($fields); unset($fields['myvalue']); $fields = array_flip($fields); 

Top 3 video Explaining PHP array delete by value (not key)







Related QUESTION?