How to remove specific element from an array PHP

Wahyu Raja Butar-Butar Reply 06:40
I have an array:
$array = (apple, orange, strawberry, blueberry, kiwi);
the user enters strawberry
strawberry is removed.

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

Related Posts

PHP 3616927475887802540
Comments
0 Comments
Facebook Comments by Media Blogger

Post a Comment

Search

Google+ Followers

Popular Posts

Translate