How to delete specific elements from an array
P粉141455512
2023-08-20 16:20:23
<p>How do I remove an element from an array when I know its value? For example: </p>
<p>I have an array:</p>
<pre class="brush:php;toolbar:false;">$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');</pre>
<p>User input<code>strawberry</code></p>
<p><code>strawberry</code> was removed from <code>$array</code>. </p>
<p>The complete explanation is as follows:</p>
<p>I have a database that stores a comma separated list of items. The code pulls the list based on the location selected by the user. So, if they select strawberry, the code pulls out every entry that contains strawberry and uses split() to convert it to an array. I want to remove the user selected item from the array, for example strawberries in this example. </p>
Use
array_diff()
for a one-line solution:...No need for extra functions or foreach loops.
Use the
Thearray_search
function to get the key and theunset
function to remove it if found:array_search
function returns false when no item is found (returns null before PHP 4.2.0).If there may be multiple items with the same value, you can use the
array_keys
function to get the keys of all items: