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