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

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

问题描述

当我知道元素的值时,如何从数组中删除元素?例如:

How do I remove an element from an array when I know the element's value? for example:

我有一个数组:

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

用户输入草莓

strawberry$array 中移除.

全面解释:

我有一个数据库,用于存储以逗号分隔的项目列表.该代码根据该选项所在的用户选择拉入列表.因此,如果他们选择草莓,他们的代码会在草莓所在的每个条目中提取代码,然后使用 split() 将其转换为数组.我希望他们从数组中删除用户选择的项目,例如草莓.

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 获取密钥并使用 unset 删除它:

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 返回 false(null,直到 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天全站免登陆