search

Home  >  Q&A  >  body text

How to delete specific elements from an array

<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粉141455512P粉141455512509 days ago556

reply all(2)I'll reply

  • P粉511757848

    P粉5117578482023-08-21 13:42:03

    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.

    reply
    0
  • P粉254077747

    P粉2540777472023-08-21 12:54:10

    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]);
    }

    reply
    0
  • Cancelreply