Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Delete PHP array by value (not key)

I have a PHP array as follows:

$messages = [312, 401, 1599, 3, ...];

I want to delete the element containing the value $del_val (for example, $del_val=401), but I don't know its key. This might help: each value can only be there once.

I'm looking for the simplest function to perform this task, please.
by

3 Answers

Kajalsi45d
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]);
}
RoliMishra
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]).
kshitijrana14
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.

Login / Signup to Answer the Question.