How to delete specific elements from an array
P粉141455512
P粉141455512 2023-08-20 16:20:23
0
2
587
<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>
P粉141455512
P粉141455512

reply all(2)
P粉511757848

Use array_diff() for a one-line solution:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //再加一个'strawberry'以证明它可以删除字符串的多个实例
$array_without_strawberries = array_diff($array, array('strawberry'));
print_r($array_without_strawberries);

...No need for extra functions or foreach loops.

P粉254077747

Use the array_search function to get the key and the unset function to remove it if found:

if (($key = array_search('strawberry', $array)) !== false) {
    unset($array[$key]);
}
The

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:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template