Sunday 12 November 2017

PHP: How to remove specific element from an array?

itemprop="text">


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.



Answer




Use rel="noreferrer">array_search to get the key and
remove it with rel="noreferrer">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 rel="noreferrer">array_keys to get the keys to all
items:



foreach (array_keys($array,
'strawberry') as $key) {

unset($array[$key]);
}



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...