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

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


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


A better solution is to use the array_filter function:

$display_related_tags =    array_filter($display_related_tags, function($e) use($found_tag){        return $e != $found_tag['name'];    });

As the php documentation reads:

As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.

In PHP 7, foreach does not use the internal array pointer.


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