1193

I have a PHP array like so:

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

Given that the values in the array are unique, how can I delete the element with a given value (without knowing its key)?

3
  • 2
    @Adam Strudwick But if you have many deletions on this array, would it be better to iterate it once and make its key same as value? Commented Nov 14, 2013 at 9:00
  • 1
    Same question : stackoverflow.com/questions/1883421/… Commented Jun 29, 2016 at 18:28
  • posible duplicate of PHP Delete an element from an array Commented Feb 12, 2018 at 7:34

21 Answers 21

2036

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.

Sign up to request clarification or add additional context in comments.

18 Comments

Would $messages = array_diff($messages, array($del_val)) work too? Would it be better in performance?
@Adam Why not test it out? My feeling is that array_diff() would be slower as it's comparing two arrays, not simply searching through one like array_search().
Even though this is valid, you should avoid assigning values in statements like that. It will only get you into trouble.
If the value you're searching for has a key of 0 or any other falsey value, it won't unset the value and your code won't work. You should test $key === false. (edit- you got it)
Note that this will not reset array keys.
|
969

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.

13 Comments

this only works for objects that can be converted to a string
It's worth noting that for some reason array_diff uses (string) $elem1 === (string) $elem2 as its equality condition, not $elem1 === $elem2 as you might expect. The issue pointed out by @nischayn22 is a consequence of this. If you want something to use as a utility function that will work for arrays of arbitrary elements (which might be objects), Bojangle's answer might be better for this reason.
Also note that this method performs a sort internally for each argument to array_diff() and thus nudges the runtime up to O(n lg n) from O(n).
I don't know why, but the [$element] in square brackets breaks my code, while array($element) is working.
For force accept string, int or array, the way is: return array_diff($array (array)$element)
|
184
+50
Answer recommended by PHP Collective

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

4 Comments

Yes, this is effective for selecting multiple array items/keys.
This is the best for arrays that may not contain all unique values.
The problem is that it leaves the index of the keys onsorted: [0] - a, [2] - b (the [1] is gone but the array still misses it)
@Rodniko in which case you would need array_values() as well; the remaining keys are still in the same order though, so technically it's not "unsorted"
79

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

Comments

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

7 Comments

This only works when your array does not contain duplicate values other than the ones you're trying to remove.
@jberculo and sometimes that exactly what you need, in some cases it saves me doing a array unique on it aswel
Maybe, but I would use functions specifically designed to do that, instead of being just a fortunate side effect of a function that is basically used and intended for something else. It would also make your code less transparent.
The message states "each value can only be there once" this should work. It would have been nice if the poster had used the smae variable names though and added a little explenation
apparently this is fastest as compared to selected solution, i did small benchmarking.
|
42

With PHP 7.4 using arrow functions:

$messages = array_filter($messages, fn ($m) => $m != $del_val);

To keep it a non-associative array wrap it with array_values():

$messages = array_values(array_filter($messages, fn ($m) => $m != $del_val));

1 Comment

This is awesome. Easy to understand, practical use of arrow functions which are new to me. I needed to remove part of an array of associative arrays based on a nested value which isn't really possible with any of the other answers. I had resorted to using a foreach() loop, but this is much more concise.
39

The following answer using array_splice fails at 2 scenarios

  1. If the searched value is not found, it removes the first element
  2. It won't work with associative arrays.

Thus, it is not a good way to do. Not deleting my original answer because many others have also mentioned this array_splice as the best way. Therefore, updated my previous answer with reasons for it being the bad way to do.

Better if only removing 1 value from simple array

array_filter($array, fn($e) => $e !== $value)

Previous Original Answer Below

The Best way is array_splice

array_splice($array, array_search(58, $array ), 1);

Reason for Best is here at http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/

5 Comments

This will not work on associative arrays and arrays that have gaps in their keys, e.g. [1, 2, 4 => 3].
No sorry this will work. Please read the article I have provided link
It won't. Consider the array of my above comment; after I use your code to remove the value 3, the array will be [1, 2, 3]; in other words, the value wasn't removed. To be clear, I'm not saying it fails in all scenarios, just this one.
array_splice is the best method, unset will not adjust the array indexes after deleting
Not a good solution. If you'll search for the value that doesn't exists: array_search will return "false", and array_splice will turn it into 0 and will remove first element in array. $array = [3344, 4455, 5566]; array_splice($array, array_search(1122, $array), 1); // as result $array = [4455, 5566]
34

Or simply, manual way:

foreach ($array as $key => $value){
    if ($value == $target_value) {
        unset($array[$key]);
    }
}

This is the safest of them because you have full control on your array

1 Comment

Using array_splice() instead of unset() will reorder the array indexes too, which could be better in this case.
20
function array_remove_by_value($array, $value)
{
    return array_values(array_diff($array, array($value)));
}

$array = array(312, 401, 1599, 3);

$newarray = array_remove_by_value($array, 401);

print_r($newarray);

Output

Array ( [0] => 312 [1] => 1599 [2] => 3 )

2 Comments

i'm not sure if this is faster since this solution involves multiple function calls.
Code-only answers are low-value on Stack Overflow. Every answer should include an explanation of how it works or why you feel it is good advice versus other techniques.
15

you can do:

unset($messages[array_flip($messages)['401']]);

Explanation: Delete the element that has the key 401 after flipping the array.

4 Comments

You have to be very careful if you want to preserve the state. because all future code will have to have values instead of keys.
@saadlulu $messages array will not be flipped since array_flip() does not effect the original array, so the resulting array after applying the previous line will be the same except that the unwanted result will be removed.
not sure if this is correct, what if there are several elements with the value of 401?
This will still preserve keys.
14

PHP 7.4 or above

function delArrValues(array $arr, array $remove) {
    return array_filter($arr, fn($e) => !in_array($e, $remove));
};

So, if you have the array as

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

and you want to remove both 3, 312 from the $messages array, You'd do this

delArrValues($messages, [3, 312])

It would return

[401, 1599]

The best part is that you can filter multiple values easily, even there are multiple occurrences of the same value.

1 Comment

Note that an expanded form of the array_filter version could be used on older versions of php, such as: ` array_filter( $arr, function($arg) use ($black_list) { return !in_array($arg, $black_list); } ); `
12

The accepted answer converts the array to associative array, so, if you would like to keep it as a non-associative array with the accepted answer, you may have to use array_values too.

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

The reference is linked here

Comments

8

To delete multiple values try this one:

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

1 Comment

This will be less efficient than looping over the input one time (and there are multiple tools for doing this). Imagine you are iterating an indexed array with 10 elements and you want to remove the elements at index 4 and 8. This will iterate from 0 to 4, then unset element [4], then it will iterate 0 to 8, then unset element [8]. See how this technique will needlessly check [0], [1], [2], [3] more than once. I would never use this technique for any reason and I recommend that all researchers take a wide birth from this answer. (this is the reason for my DV)
7

If you don't know its key it means it doesn't matter.

You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.

$messages=array();   
$messages[312] = 312;    
$messages[401] = 401;   
$messages[1599] = 1599;   
$messages[3] = 3;    

unset($messages[3]); // no search needed

2 Comments

Only works for objects that can be converted to a string.
And no two values are the same. Which VERY often is not the case, although in the OP case, it seems to be.
6

Borrowed the logic of underscore.JS _.reject and created two functions (people prefer functions!!)

array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)

function array_reject_value(array &$arrayToFilter, $deleteValue) {
    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if ($value !== $deleteValue) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)

function array_reject(array &$arrayToFilter, callable $rejectCallback) {

    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if (!$rejectCallback($value, $key)) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

So in our current example we can use the above functions as follows:

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);

or even better: (as this give us a better syntax to use like the array_filter one)

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
    return $value === 401;
});

The above can be used for more complicated stuff like let's say we would like to remove all the values that are greater or equal to 401 we could simply do this:

$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
    return $value >= $greaterOrEqualThan;
});

2 Comments

Isn't this reinventing filter? php.net/manual/en/function.array-filter.php
Yes indeed. As I am already saying at the post "or even better: (as this give us a better syntax to use like the array_filter one)". Sometimes you really just need to have the function reject as underscore and it is really just the opposite of the filter (and you need to get it with as less code as possible). This is what the functions are doing. This is a simple way to reject values.
4

I know this is not efficient at all but is simple, intuitive and easy to read.
So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:

$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);

foreach($arr as $key =>$value){
    if ($value !== $del_value){
        $result[$key] = $value;
    }

    //if(!in_array($value, $del_values)){
    //    $result[$key] = $value;
    //}

    //if($this->validete($value)){
    //      $result[$key] = $value;
    //}
}

return $result

Comments

4

A one-liner using the or operator:

($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);

Comments

3

Using array_filter and anonymous function:

$messages = array_filter($messages, function ($value) use ($del_val) {
    return $value != $del_val;
});

You can run a code example here: https://onlinephp.io/c/4f320

Comments

1

As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

Input:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Result:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

2 Comments

This post IN NO WAY answers the OP's question. This is the correct answer to a different question. (this is the reason for my DV)
this answer is not related to the question
0

I think the simplest way would be to use a function with a foreach loop:

//This functions deletes the elements of an array $original that are equivalent to the value $del_val
//The function works by reference, which means that the actual array used as parameter will be modified.

function delete_value(&$original, $del_val)
{
    //make a copy of the original, to avoid problems of modifying an array that is being currently iterated through
    $copy = $original;
    foreach ($original as $key => $value)
    {
        //for each value evaluate if it is equivalent to the one to be deleted, and if it is capture its key name.
        if($del_val === $value) $del_key[] = $key;
    };
    //If there was a value found, delete all its instances
    if($del_key !== null)
    {
        foreach ($del_key as $dk_i)
        {
            unset($original[$dk_i]);
        };
        //optional reordering of the keys. WARNING: only use it with arrays with numeric indexes!
        /*
        $copy = $original;
        $original = array();
        foreach ($copy as $value) {
            $original[] = $value;
        };
        */
        //the value was found and deleted
        return true;
    };
    //The value was not found, nothing was deleted
    return false;
};

$original = array(0,1,2,3,4,5,6,7,4);
$del_val = 4;
var_dump($original);
delete_value($original, $del_val);
var_dump($original);

Output will be:

array(9) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
  [8]=>
  int(4)
}
array(7) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
}

1 Comment

Simplest? Did you see, by chance, the accepted answer?
0

here is one simple but understandable solution:

$messagesFiltered = [];
foreach ($messages as $message) {
    if (401 != $message) {
        $messagesFiltered[] = $message;
    }
}
$messages = $messagesFiltered;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.