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

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

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.

ベストアンサー1

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

おすすめ記事