196

How do I remove an element from an array when I know the element's value? for example:

I have an array:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');

the user enters strawberry

strawberry is removed from $array.

To fully explain:

I have a database that stores a list of items separated by a comma. The code pulls in the list based on a user choice where that choice is located. So, if they choose strawberry they code pulls in every entry were strawberry is located then converts that to an array using split(). I want to them remove the user chosen items, for this example strawberry, from the array.

miken32
  • 42,008
  • 16
  • 111
  • 154
dcp3450
  • 10,959
  • 23
  • 58
  • 110
  • 4
    Same question: http://stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key – trante Jan 10 '13 at 19:42
  • 1
    Another same question : http://stackoverflow.com/questions/1883421/removing-array-item-by-value – Eric Lavoie Jun 29 '16 at 18:29
  • 1
    more same question: https://stackoverflow.com/questions/369602/php-delete-an-element-from-an-array – Alex Feb 12 '18 at 07:32

22 Answers22

360

Use array_search to get the key and remove it with unset if found:

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

array_search returns false (null until PHP 4.2.0) if no item has been found.

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 1
    Getting an odd result. I used your first suggestion since there will always only be one instance. To test it I simply had it output the key value. Worked. However, it wont unset. – dcp3450 Mar 15 '10 at 17:50
  • 1
    while(odbc_fetch_row($runqueryGetSubmenus)) { $submenuList = odbc_result($runqueryGetSubmenus,"submenus"); $submenuArray = split(',',$submenuList); if (($key = array_search($name,$submenuArray)) !== false) { unset($submenuArray[$key]); } } – dcp3450 Mar 15 '10 at 18:02
  • @dcp3450: And what do you do with `$submenuArray`? (Note that with each loop `$submenuArray` will be overwritten.) – Gumbo Mar 15 '10 at 18:09
  • i updated my question to better explain. Basically the code loops through entries in a database removing the chosen items, "strawberry" in this example. So, the user enters a selection => the code searches under submenus and finds any list that has that option => turns that list into an array => removes the chosen option. – dcp3450 Mar 15 '10 at 18:13
  • 1
    I got it! I wasn't rewriting the new array back to the DB. Easy to miss stuff when you stare at code for so long. – dcp3450 Mar 15 '10 at 18:23
  • @dcp3450 Agree with @Gumbo. In the sample code you posted above, You aren't doing anything with $submenuArray after removing the user selected option and that variable is constantly reused in the loop. You need to save it to the database or use a multidimensional array to access your modified $submenuArray later. – ghoppe Mar 15 '10 at 18:26
  • This solution is not efficient since it uses a full search and iteration over the whole array, or can only remove one entry at a time, and manipulates the original array (or needs extra memory if manipulation is not desired) I suggest [ills' answer](https://stackoverflow.com/a/18852178/3994502) instead. – Tala Jul 10 '19 at 08:13
185

Use array_diff() for 1 line solution:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //throw in another 'strawberry' to demonstrate that it removes multiple instances of the string
$array_without_strawberries = array_diff($array, array('strawberry'));
print_r($array_without_strawberries);

...No need for extra functions or foreach loop.

mbomb007
  • 3,788
  • 3
  • 39
  • 68
ills
  • 1,851
  • 1
  • 11
  • 2
  • Although if `strawberry` is not in the initial array, it will become available in the `$array_without_strawberries` array - dangerous code if you want to ensure that a given element is not in an array. – Erfan Jul 28 '17 at 02:10
  • 10
    @Erfan Your claim is wrong. `$a = array_diff(array(), array('strawberry'));` - $a is an empty array. – bancer Aug 03 '17 at 21:29
  • 2
    You're right @bancer - I was probably thinking of array_intersect or something. – Erfan Aug 04 '17 at 07:32
  • 1
    From a performance perspective: this creates two new arrays. So is the `unset` approach the better one? – robsch Nov 02 '17 at 09:59
  • 1
    @robsch Yes. The `unset()` does the same thing and just unsets one element. – Alexis Wilke Apr 22 '22 at 14:18
45
if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}
jayadevkv
  • 384
  • 3
  • 16
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 2
    You should test if *strawberry* is in the array at all. – Gumbo Mar 15 '10 at 17:10
  • Following Gumbo's advice modified answer to include verification of the element before removing it from the array. – John Conde Mar 15 '10 at 17:18
  • 2
    Also keep in mind that the indices aren't realigned after deleting a particular element. In other words, the index sequence will have gaps then. If you delete 'strawberry' from your example, 'kiwi' will still have index 4, and index 2 will simply disappear. It matters if your code relies on the completeness of the index sequence, as for example for($i = 0; $i <.., $i++) loops do. – the-banana-king Mar 15 '10 at 17:32
  • 2
    To add to what the-banana-king said, if you want to reindex the array, simply do `$my_array = array_values($my_array);`. – ryeguy Mar 15 '10 at 17:41
  • 2
    While this solution is correct, it searches the array TWICE (`in_array` and `array_search`). Using the return of `array_search` as in Gumbo's answer is more effective – Bogdan D Mar 19 '13 at 11:41
28

If you are using a plain array here (which seems like the case), you should be using this code instead:

if (($key = array_search('strawberry', $array)) !== false) {
    array_splice($array, $key, 1);
}

unset($array[$key]) only removes the element but does not reorder the plain array.

Supposingly we have an array and use array_splice:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
array_splice($array, 2, 1);
json_encode($array); 
// yields the array ['apple', 'orange', 'blueberry', 'kiwi']

Compared to unset:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[2]);
json_encode($array);
// yields an object {"0": "apple", "1": "orange", "3": "blueberry", "4": "kiwi"}

Notice how unset($array[$key]) does not reorder the array.

Hasse Björk
  • 1,431
  • 13
  • 19
ericluwj
  • 465
  • 6
  • 5
26

You can do it with a single line, which will remove the element from the array.

$array = array_diff($array,['strawberry']);
Brad Ahrens
  • 4,864
  • 5
  • 36
  • 47
dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
15

You can use array filter to remove the items by a specific condition on $v:

$arr = array_filter($arr, function($v){
    return $v != 'some_value';
});
Emma
  • 27,428
  • 11
  • 44
  • 69
srcspider
  • 10,977
  • 5
  • 40
  • 35
  • 1
    Downvote. This low-quality (because it is a code-only answer and gives a parsing error) is a duplicate of D.Martin's method that merely uses a anonymous function inside `array_filter()`. While I personally would be using an anonymous function in my implementation, I believe the correct action on SO would be to comment on or edit D.Martin's answer if you wish to make a micro-improvement so that this page doesn't become bloated. Please delete this duplicate answer. – mickmackusa Apr 30 '17 at 03:55
4

Will be like this:

 function rmv_val($var)
 {
     return(!($var == 'strawberry'));
 }

 $array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');

 $array_res = array_filter($array, "rmv_val");
D.Martin
  • 116
  • 1
3

I'm currently using this function:

function array_delete($del_val, $array) {
    if(is_array($del_val)) {
         foreach ($del_val as $del_key => $del_value) {
            foreach ($array as $key => $value){
                if ($value == $del_value) {
                    unset($array[$key]);
                }
            }
        }
    } else {
        foreach ($array as $key => $value){
            if ($value == $del_val) {
                unset($array[$key]);
            }
        }
    }
    return array_values($array);
}

You can input an array or only a string with the element(s) which should be removed. Write it like this:

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$detils = array_delete(array('orange', 'apple'), $detils);

OR

$detils = array_delete('orange', $detils);

It'll also reindex it.

jankal
  • 1,090
  • 1
  • 11
  • 28
3

This is a simple reiteration that can delete multiple values in the array.

    // Your array
    $list = array("apple", "orange", "strawberry", "lemon", "banana");

    // Initilize what to delete
    $delete_val = array("orange", "lemon", "banana");

    // Search for the array key and unset   
    foreach($delete_val as $key){
        $keyToDelete = array_search($key, $list);
        unset($list[$keyToDelete]);
    }
mmr
  • 516
  • 11
  • 30
  • This is an inefficient, home-rolled replacement for what the developers of PHP have already created in `array_diff()`. How did this get three upvotes. No one should be finding this answer helpful or using it in their own projects. I recommend deleting this answer -- this would serve to free your account of a low-quality answer, reduce the answer-bloat on this page, and earn you a Disciplined badge. I will postpone my downvote so that you have time to delete for a reward. – mickmackusa Apr 30 '17 at 03:42
3

Use this simple way hope it will helpful

foreach($array as $k => $value)
    {
      
        if($value == 'strawberry')
        {
          unset($array[$k]);
        }
    }
Siraj Ali
  • 526
  • 6
  • 13
2

This question has several answers but I want to add something more because when I used unset or array_diff I had several problems to play with the indexes of the new array when the specific element was removed (because the initial index are saved)

I get back to the example :

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));

or

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);

If you print the result you will obtain :

foreach ($array_without_strawberries as $data) {
   print_r($data);
}

Result :

> apple
> orange
> blueberry
> kiwi

But the indexes will be saved and so you will access to your element like :

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi

And so the final array are not re-indexed. So you need to add after the unset or array_diff:

$array_without_strawberries = array_values($array);

After that your array will have a normal index :

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi

Related to this post : Re-Index Array

enter image description here

Hope it will help

Jordan Montel
  • 8,227
  • 2
  • 35
  • 40
1

A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys() on it when you want to actual array. That way you don't need to use array_search to find your element.

crmpicco
  • 16,605
  • 26
  • 134
  • 210
jishi
  • 24,126
  • 6
  • 49
  • 75
1

The answer to PHP array delete by value (not key) Given by https://stackoverflow.com/users/924109/rok-kralj

IMO is the best answer as it removes and does not mutate

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. It might be a bit slower because of this.

hounded
  • 666
  • 10
  • 21
1

I was looking for the answer to the same question and came across this topic. I see two main ways: the combination of array_search & unset and the use of array_diff. At first glance, it seemed to me that the first method would be faster, since does not require the creation of an additional array (as when using array_diff). But I wrote a small benchmark and made sure that the second method is not only more concise, but also faster! Glad to share this with you. :)

https://glot.io/snippets/f6ow6biaol

Developer
  • 131
  • 1
  • 7
0

I would prefer to use array_key_exists to search for keys in arrays like:

Array([0]=>'A',[1]=>'B',['key'=>'value'])

to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().

I think it will help someone.

Manolo
  • 24,020
  • 20
  • 85
  • 130
ddsultan
  • 2,027
  • 1
  • 19
  • 19
0

Create numeric array with delete particular Array value

    <?php
    // create a "numeric" array
    $animals = array('monitor', 'cpu', 'mouse', 'ram', 'wifi', 'usb', 'pendrive');

    //Normarl display
    print_r($animals);
    echo "<br/><br/>";

    //If splice the array
    //array_splice($animals, 2, 2);
    unset($animals[3]); // you can unset the particular value
    print_r($animals);

    ?>

You Can Refer this link..

Community
  • 1
  • 1
  • Downvote. The question clearly asks to remove a value based on the value (not the key). This answer is useless, please delete. – mickmackusa Apr 30 '17 at 00:54
0
$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}
jvk
  • 2,133
  • 3
  • 19
  • 28
-1

Using array_seach(), 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 "falsey" 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.

Ravinder Singh
  • 3,113
  • 6
  • 30
  • 46
  • 3
    Downvote. This a duplicate of Gumbo's method (currently the accepted solution) which was posted years before yours. Duplicate answers have no value and only cause unnecessary page bloat. Please delete your answer. If you wish to explain Gumbo's answer, do so with an edit on his answer or ask Gumbo to expand his own answer.. – mickmackusa Apr 30 '17 at 01:20
-1
unset($array[array_search('strawberry', $array)]);
max li
  • 2,417
  • 4
  • 30
  • 44
  • 3
    Downvote. The `array_search()`-`unset()` method was already posted by John Conde years before yours. Duplicate answers have no value to readers and are actually an inconvenience because of time wasted while scrolling and reading redundant information. Please delete this answer. – mickmackusa Apr 30 '17 at 01:06
-1
<?php 
$array = array("apple", "orange", "strawberry", "blueberry", "kiwi");
$delete = "strawberry";
$index = array_search($delete, $array);
array_splice($array, $index, 1);
var_dump($array);
?>
  • 2
    You can improve this answer by writing a sentence or two about a) what the code does, and b) why you think it is an option among all the other answers. – Robin Mackenzie Oct 15 '17 at 00:08
-1
foreach ($get_dept as $key5 => $dept_value) {
                if ($request->role_id == 5 || $request->role_id == 6){
                    array_splice($get_dept, $key5, 1);
                }
            }
  • 4
    In addition to the answer you've provided, please consider providing a brief explanation of why and how this fixes the issue. – jtate Nov 15 '19 at 13:43
-2
$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
     function remove_embpty($values)
     {
        if($values=='orange')
        {
            $values='any name';
        }
        return $values;
     }
     $detils=array_map('remove_embpty',$detils);
    print_r($detils);
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64