How do you remove an array element in a foreach loop?

ajsie picture ajsie · Dec 22, 2009 · Viewed 142.8k times · Source

I want to loop through an array with foreach to check if a value exists. If the value does exist, I want to delete the element which contains it.

I have the following code:

foreach($display_related_tags as $tag_name) {
    if($tag_name == $found_tag['name']) {
        // Delete element
    }
}

I don't know how to delete the element once the value is found. How do I delete it?

I have to use foreach for this problem. There are probably alternatives to foreach, and you are welcome to share them.

Answer

Gumbo picture Gumbo · Dec 22, 2009

If you also get the key, you can delete that item like this:

foreach ($display_related_tags as $key => $tag_name) {
    if($tag_name == $found_tag['name']) {
        unset($display_related_tags[$key]);
    }
}