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.


如果您还获得了密钥,则可以像这样删除该项目:

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.


foreach($display_related_tags as $key => $tag_name)
{
    if($tag_name == $found_tag['name'])
        unset($display_related_tags[$key];
}
链接地址: http://www.djcxy.com/p/5100.html

上一篇: 在(可能)关联数组中获取第一个键?

下一篇: 你如何在foreach循环中移除一个数组元素?