Removing array item by value [duplicate] Ask Question

Removing array item by value [duplicate] Ask Question

I need to remove array item with given value:

if (in_array($id, $items)) {
    $items = array_flip($items);
    unset($items[ $id ]);
    $items = array_flip($items);
}

Could it be done in shorter (more efficient) way?

ベストアンサー1

It can be accomplished with a simple one-liner.

Having this array:

$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');

You can do:

$arr = array_diff($arr, array('remove_me', 'remove_me_also'));

And the value of $arr will be:

array('nice_item', 'another_liked_item')

おすすめ記事