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 21:03

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]);
    }
查看更多
素衣白纱
3楼-- · 2019-01-02 21:05

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.

查看更多
登录 后发表回答