PHP: How to remove specific element from an array?

2019-01-02 20:19发布

How do I remove an element from an array when I know the elements name? for example:

I have an array:

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

the user enters strawberry

strawberry is removed.

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.

标签: php arrays
20条回答
孤独寂梦人
2楼-- · 2019-01-02 20:49

$arr = \array_filter($arr, function ($v) { return $v != 'some_value'; }

查看更多
无色无味的生活
3楼-- · 2019-01-02 20:49

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");
查看更多
浅入江南
4楼-- · 2019-01-02 20:50

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.

查看更多
时光乱了年华
5楼-- · 2019-01-02 20:51

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.

查看更多
浮光初槿花落
6楼-- · 2019-01-02 20:51

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.

查看更多
千与千寻千般痛.
7楼-- · 2019-01-02 20:54

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.

查看更多
登录 后发表回答