PHP array delete by value (not key) PHP array delete by value (not key) php php

PHP array delete by value (not key)


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.


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.


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]).