PHP:如何从一个数组中删除特定元素? [英] PHP: How to remove specific element from an array?

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

问题描述

我如何从一个数组中删除元素,当我知道的元素名称?例如:

How do I remove an element from an array when I know the elements name? for example:

我有一个数组:

$array = (apple, orange, strawberry, blueberry, kiwi);

用户输入草莓

草莓被删除。

要充分说明:

我有一个存储用逗号分隔的项目列表的数据库。在code在根据用户的选择,其中该选择位于列表拉。所以,如果他们选择他们的草莓code拉动每个条目都草莓位于然后转换了一种使用数组拆分()。我想他们删除该用户选择的项目,对本实施例的草莓,从阵列

I have a database that stores a list of items separated by a comma. The code pulls in the list based on a user choice where that choice is located. So, if they choose strawberry they code pulls in every entry were strawberry is located then converts that to an array using split(). I want to them remove the user chosen items, for this example strawberry, from the array.

推荐答案

使用 array_search 拿到钥匙,并与 取消设置 若发现其删除:

Use array_search to get the key and remove it with unset if found:

if (($key = array_search('strawberry', $array)) !== false) {
    unset($array[$key]);
}

array_search 返回的(的PHP之前4.2.0),如果项目不被发现。

array_search returns false (null until PHP 4.2.0) if no item has been found.

如果可以有多个项目进行相同的值,可以使用 array_keys 拿到钥匙的所有项目:

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}

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

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