199

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.

3

23 Answers 23

367

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]);
}
Sign up to request clarification or add additional context in comments.

7 Comments

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.
while(odbc_fetch_row($runqueryGetSubmenus)) { $submenuList = odbc_result($runqueryGetSubmenus,"submenus"); $submenuArray = split(',',$submenuList); if (($key = array_search($name,$submenuArray)) !== false) { unset($submenuArray[$key]); } }
@dcp3450: And what do you do with $submenuArray? (Note that with each loop $submenuArray will be overwritten.)
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.
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.
|
190

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.

5 Comments

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 Your claim is wrong. $a = array_diff(array(), array('strawberry')); - $a is an empty array.
You're right @bancer - I was probably thinking of array_intersect or something.
From a performance perspective: this creates two new arrays. So is the unset approach the better one?
@robsch Yes. The unset() does the same thing and just unsets one element.
45
if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}

5 Comments

You should test if strawberry is in the array at all.
Following Gumbo's advice modified answer to include verification of the element before removing it from the array.
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.
To add to what the-banana-king said, if you want to reindex the array, simply do $my_array = array_values($my_array);.
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
33

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

$array = array_diff($array,['strawberry']);

2 Comments

This should be the accepted answer, as unset leaves a "hole" in the array.
maybe , but the code should be simple...kiss principle
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.

2 Comments

Officially unset does not return anything. So json_encode(unset($array[2])) is not appropiate for a comparison.
this is exactly what i need, thaks to ericluwj
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';
});

1 Comment

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.
5

Use this simple way hope it will helpful

foreach($array as $k => $value)
    {
      
        if($value == 'strawberry')
        {
          unset($array[$k]);
        }
    }

Comments

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");

Comments

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]);
    }

1 Comment

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.
2

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.

1 Comment

This is horribly convoluted and loopy. How did this gain 3 upvotes?!?
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

Comments

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.

1 Comment

Your post is a comment not an answer. Please delete and post under the question itself.
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.

Comments

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

Comments

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.

Comments

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

1 Comment

Downvote. The question clearly asks to remove a value based on the value (not the key). This answer is useless, please delete.
0
$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}

1 Comment

This answer doesn't even remove the required option.
-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.

1 Comment

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..
-1
unset($array[array_search('strawberry', $array)]);

1 Comment

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.
-1
<?php 
$array = array("apple", "orange", "strawberry", "blueberry", "kiwi");
$delete = "strawberry";
$index = array_search($delete, $array);
array_splice($array, $index, 1);
var_dump($array);
?>

1 Comment

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.
-1
foreach ($get_dept as $key5 => $dept_value) {
                if ($request->role_id == 5 || $request->role_id == 6){
                    array_splice($get_dept, $key5, 1);
                }
            }

1 Comment

In addition to the answer you've provided, please consider providing a brief explanation of why and how this fixes the issue.
-1

dılo sürücü's answer was close to what I was looking for, but.

If you need to keep the index consistent because you save it to a DB field as json instead of as a comma separated string then you have to re-index it:

$array = array_values(array_diff($array,['strawberry']));

result without array_values

(
    [0] => 'apple'
    [1] => 'orange'
    [3] => 'blueberry'
    [4] => 'kiwi'
)

result with array_values

(
    [0] => 'apple'
    [1] => 'orange'
    [2] => 'blueberry'
    [3] => 'kiwi'
)

Comments

-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);

3 Comments

Please also add explanation. How it solves the problem.
your answer replace one element of array to another NO to remove an element
Downvote. This answer does not provide the expected output. Please delete this incorrect answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.