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.
The answer to PHP array delete by value (not key) Given by https://stackoverflow.com/users/924109/rok-kralj
IMO is the best answer as it removes and does not mutate
It generalizes nicely, you can remove as many elements as you like at the same time, if you want.
Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. It might be a bit slower because of this.
Create numeric array with delete particular Array value
You Can Refer this link..
Using
array_seach()
, try the following:array_search()
returns the key of the element it finds, which can be used to remove that element from the original array usingunset()
. It will returnFALSE
on failure, however it can return a "falsey" value on success (your key may be0
for example), which is why the strict comparison!==
operator is used.The
if()
statement will check whetherarray_search()
returned a value, and will only perform an action if it did.I was looking for the answer to the same question and came across this topic. I see two main ways: the combination of
array_search
&unset
and the use ofarray_diff
. At first glance, it seemed to me that the first method would be faster, since does not require the creation of an additional array (as when usingarray_diff
). But I wrote a small benchmark and made sure that the second method is not only more concise, but also faster! Glad to share this with you. :)https://glot.io/snippets/f6ow6biaol