如何在 foreach 循环中删除数组元素? [英] How do you remove an array element in a foreach loop?

查看:85
本文介绍了如何在 foreach 循环中删除数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 foreach 遍历一个数组来检查一个值是否存在.如果该值确实存在,我想删除包含它的元素.

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.

我有以下代码:

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?

我必须使用 foreach 来解决这个问题.foreach 可能还有其他替代方案,欢迎您分享.

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

推荐答案

如果你也拿到了钥匙,你可以像这样删除那个项目:

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

这篇关于如何在 foreach 循环中删除数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆