PHP数组由值(不是键)删除 [英] PHP array delete by value (not key)

查看:124
本文介绍了PHP数组由值(不是键)删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP数组如下:

I have a PHP array as follows:

$messages = array();
$messages[1] = 312;
$messages[2] = 401;
$messages[3] = 1599;
$messages[4] = 3;
...

我要删除包含该值的元素 $ del_val (例如, $ del_val = 401 ),但我不知道它的密钥。这可能帮助:的每个值只能有一次

I want to delete the element containing the value $del_val (for example, $del_val=401), but I don't know its key. This might help: each value can only be there once.

我在寻找最简单的函数来执行这个任务吧。

I'm looking for the simplest function to perform this task please.

推荐答案

使用 array_search() 取消设置 ,请尝试以下操作:

Using array_search() and unset, try the following:

if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search()返回它找到的元素,它可以用于使用从原来的数组中删除该元素的键未设置() 。它会返回 FALSE 失败,但它可以返回上成功的假y值(你的密钥可以 0 例如),这就是为什么严格比较!== 运算符。

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

如果()语句将检查是否 array_search()返回的值,并且将只执行一个动作如果它这样做。

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

这篇关于PHP数组由值(不是键)删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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