ajsie ajsie - 6 months ago 12
PHP Question

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

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

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