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.
$arr = \array_filter($arr, function ($v) { return $v != 'some_value'; }
Will be like this:
I'm currently using this function:
You can input an array or only a string with the element(s) which should be removed. Write it like this:
OR
$detils = array_delete('orange', $detils);
It'll also reindex it.
Use
array_diff()
for 1 line solution:...No need for extra functions or foreach loop.
I would prefer to use array_key_exists to search for keys in arrays like:
Array([0]=>'A',[1]=>'B',['key'=>'value'])
to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().
I think it will help someone.
A better approach would maybe be to keep your values as keys in an associative array, and then call
array_keys()
on it when you want to actual array. That way you don't need to usearray_search
to find your element.