1128

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.

3

20 Answers 20

1946

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.

21
  • 17
    Would $messages = array_diff($messages, array($del_val)) work too? Would it be better in performance? Aug 29, 2011 at 0:55
  • 10
    @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().
    – Bojangles
    Aug 29, 2011 at 0:57
  • 26
    Even though this is valid, you should avoid assigning values in statements like that. It will only get you into trouble.
    – adlawson
    Aug 29, 2011 at 1:05
  • 17
    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)
    – evan
    Aug 29, 2011 at 1:11
  • 6
    Note that this will not reset array keys. Mar 8, 2013 at 5:29
883

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.

16
  • 37
    this only works for objects that can be converted to a string
    – nischayn22
    Aug 12, 2012 at 20:20
  • 8
    I seem to be getting a 'Parse Error' for saying [$element], I used array($element) instead. No biggie, but just wanted anyone who had a similar issue to know that they weren't alone
    – Angad
    Aug 26, 2013 at 14:11
  • 9
    Sure, I have assumed PHP 5.4 is now in majority to drop the old notation. Thanks for the remark.
    – Rok Kralj
    Aug 26, 2013 at 18:57
  • 27
    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.
    – Mark Amery
    Jan 1, 2014 at 22:39
  • 6
    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).
    – Ja͢ck
    Jul 14, 2014 at 6:12
169
+50

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

5
  • 1
    Yes, this is effective for selecting multiple array items/keys. Aug 28, 2014 at 4:52
  • 4
    This is the best for arrays that may not contain all unique values.
    – Derokorian
    Oct 22, 2014 at 16:53
  • 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
    Dec 26, 2014 at 5:25
  • 3
    @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"
    – Ja͢ck
    Dec 26, 2014 at 5:27
  • Great answer - I had no idea array_keys() could do a search. Jan 12, 2022 at 4:09
71

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

50
$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);
7
  • 15
    This only works when your array does not contain duplicate values other than the ones you're trying to remove.
    – jberculo
    Jun 2, 2014 at 8:35
  • 3
    @jberculo and sometimes that exactly what you need, in some cases it saves me doing a array unique on it aswel
    – DarkMukke
    Nov 14, 2014 at 15:06
  • 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.
    – jberculo
    Nov 14, 2014 at 16:08
  • 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
    – Raatje
    Sep 24, 2015 at 8:37
  • 2
    apparently this is fastest as compared to selected solution, i did small benchmarking.
    – user1642018
    Oct 20, 2017 at 8:35
34

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/

4
  • 6
    This will not work on associative arrays and arrays that have gaps in their keys, e.g. [1, 2, 4 => 3].
    – Ja͢ck
    Jul 14, 2014 at 6:27
  • No sorry this will work. Please read the article I have provided link
    – Airy
    Jul 15, 2014 at 12:05
  • 6
    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.
    – Ja͢ck
    Jul 15, 2014 at 12:10
  • 1
    array_splice is the best method, unset will not adjust the array indexes after deleting
    – Raaghu
    Nov 7, 2015 at 14:23
32

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
  • 1
    Using array_splice() instead of unset() will reorder the array indexes too, which could be better in this case. Dec 18, 2015 at 15:31
29

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
  • 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. Jan 12, 2022 at 4:21
18
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
  • 2
    i'm not sure if this is faster since this solution involves multiple function calls. Nov 18, 2016 at 6:56
  • 2
    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. Jun 30, 2020 at 7:33
16

you can do:

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

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

4
  • 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
    Jun 30, 2015 at 13:18
  • 2
    @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.
    – Qurashi
    Jun 30, 2015 at 18:46
  • 3
    not sure if this is correct, what if there are several elements with the value of 401?
    – Zippp
    Mar 6, 2019 at 14:54
  • This will still preserve keys. Apr 8, 2020 at 7:15
10

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
  • 1
    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); } ); ` Mar 10, 2022 at 6:01
9

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

8

To delete multiple values try this one:

while (($key = array_search($del_val, $messages)) !== false) 
{
    unset($messages[$key]);
}
1
  • 4
    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) Jun 30, 2020 at 5:53
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
  • Only works for objects that can be converted to a string. Sep 27, 2017 at 18:20
  • And no two values are the same. Which VERY often is not the case, although in the OP case, it seems to be.
    – Roemer
    Nov 22, 2021 at 20:18
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
  • 3
    Isn't this reinventing filter? php.net/manual/en/function.array-filter.php Oct 25, 2016 at 15:50
  • 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. Oct 25, 2016 at 17:12
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
4

A one-liner using the or operator:

($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);
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
  • 2
    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) Jun 30, 2020 at 6:02
  • this answer is not related to the question Sep 24, 2020 at 13:01
1

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

here is one simple but understandable solution:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.