dcp3450
dcp3450

Reputation: 11187

PHP: How to remove specific element from an array?

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.

Upvotes: 199

Views: 607145

Answers (23)

Zoltán Süle
Zoltán Süle

Reputation: 1704

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

Upvotes: -1

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

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

Upvotes: 33

Siraj Ali
Siraj Ali

Reputation: 604

Use this simple way hope it will helpful

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

Upvotes: 5

Rajendra Rajput
Rajendra Rajput

Reputation: 85

foreach ($get_dept as $key5 => $dept_value) {
                if ($request->role_id == 5 || $request->role_id == 6){
                    array_splice($get_dept, $key5, 1);
                }
            }

Upvotes: -1

srcspider
srcspider

Reputation: 11205

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

Upvotes: 15

ills
ills

Reputation: 1901

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.

Upvotes: 190

Developer
Developer

Reputation: 141

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

Upvotes: 1

Jordan Montel
Jordan Montel

Reputation: 8247

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

Upvotes: 2

ericluwj
ericluwj

Reputation: 485

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.

Upvotes: 28

Onome Mine Adamu
Onome Mine Adamu

Reputation: 35

<?php 
$array = array("apple", "orange", "strawberry", "blueberry", "kiwi");
$delete = "strawberry";
$index = array_search($delete, $array);
array_splice($array, $index, 1);
var_dump($array);
?>

Upvotes: -1

jvk
jvk

Reputation: 2211

$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}

Upvotes: 0

hounded
hounded

Reputation: 726

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.

Upvotes: 1

jishi
jishi

Reputation: 24634

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.

Upvotes: 1

Sashtha Manik
Sashtha Manik

Reputation: 121

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

Upvotes: 0

mmr
mmr

Reputation: 516

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

Upvotes: 3

jankal
jankal

Reputation: 1128

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.

Upvotes: 2

user3296940
user3296940

Reputation: 1

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

Upvotes: -2

ddsultan
ddsultan

Reputation: 2307

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.

Upvotes: 0

John Conde
John Conde

Reputation: 219914

if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}

Upvotes: 45

max li
max li

Reputation: 2467

unset($array[array_search('strawberry', $array)]);

Upvotes: -1

Ravinder Singh
Ravinder Singh

Reputation: 3133

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.

Upvotes: -1

D.Martin
D.Martin

Reputation: 116

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

Upvotes: 4

Gumbo
Gumbo

Reputation: 655735

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

Upvotes: 367

Related Questions