Friday, July 13, 2018

php - Removing array item by value



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?


Answer



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


Hope it helps write beautiful code.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...