Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 2
    You should test if strawberry is in the array at all. Commented Mar 15, 2010 at 17:10
  • Following Gumbo's advice modified answer to include verification of the element before removing it from the array. Commented Mar 15, 2010 at 17:18
  • 2
    Also keep in mind that the indices aren't realigned after deleting a particular element. In other words, the index sequence will have gaps then. If you delete 'strawberry' from your example, 'kiwi' will still have index 4, and index 2 will simply disappear. It matters if your code relies on the completeness of the index sequence, as for example for($i = 0; $i <.., $i++) loops do. Commented Mar 15, 2010 at 17:32
  • 2
    To add to what the-banana-king said, if you want to reindex the array, simply do $my_array = array_values($my_array);. Commented Mar 15, 2010 at 17:41
  • 2
    While this solution is correct, it searches the array TWICE (in_array and array_search). Using the return of array_search as in Gumbo's answer is more effective Commented Mar 19, 2013 at 11:41