PHP array delete by value (not key)(PHP数组按值删除(不是键))
问题描述
我有一个PHP数组如下:
I have a PHP array as follows:
$messages = [312, 401, 1599, 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() 和 unset,尝试以下方法:
Using array_search() and unset, try the following:
if (($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
}
array_search() 返回它找到的元素的键,可用于使用 unset() 从原始数组中删除该元素.它会在失败时返回 FALSE,但是它可以在成功时返回 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.
if() 语句将检查 array_search() 是否返回了值,如果返回则只执行操作.
The if() statement will check whether array_search() returned a value, and will only perform an action if it did.
这篇关于PHP数组按值删除(不是键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP数组按值删除(不是键)
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Laravel 仓库 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
