php - PHP array_search 函数无法正常使用返回值
问题描述
今天,我发现 php array_search函数有一个很奇怪的问题。实际上,我应用的条件是,如果 index 为0 或大于它应该通过IF条件,否则不会,但它不会像那样运行。
我分析发现,如果输出为FALSE则(FALSE >= 0)它也通过比较值的条件,不知道为什么。谁能解释这个问题?
似乎不是array_search函数问题,但我在使用此函数时遇到了问题。
$allowedJobCodesForCC = array( "xyz", "abc");
/* output if value not found in array
var_dump(array_search(strtolower(trim('xyzfd')), $allowedJobCodesForCC));
*/
$output = array_search(strtolower(trim('xyz')), $allowedJobCodesForCC); //output : false
/* array_search function treating false return value and passing it to the condition */
if($output >= 0){
echo 'passed'; //it should not print this condition if return value is FALSE
}
/* correct fix if indexes are numeric */
if(is_numeric($output)){
echo 'passed';
}
PHP 手册: http: //php.net/manual/en/function.array-search.php
解决方案
I analysed and found, if output is FALSE then ( FALSE >= 0) its also passing the condition with comparing value, don't know why. Can anyone explain this problem ?
在http://php.net/manual/en/language.operators.comparison.php查看与各种类型的比较表
根据此表,如果将 boolean 与任何其他类型进行比较,则两个值都将转换为 boolean 然后进行比较。在您的情况下,整数0
被转换为FALSE
并最终 php 比较FALSE >= FALSE
。由于FALSE
大于或等于您的FALSE
条件返回 true。
推荐阅读
- python - (重复)获取要在列表中的前 x 个元组上执行的 for 循环
- javascript - javascript中的多个媒体查询
- python - 如何在 for 循环中创建未知数量的 TKinter 对象
- c# - 将 Id 转换为字符串类型
- c# - 快速测试显示 EF 核心与 ADO.Net 相比存在很大差异
- ruby-on-rails - 如何订购具有范围的 Rails Collection?
- c# - 尚未为此 DbContext EF Core 3.0 配置数据库提供程序
- ios - 存在如何使用 NavigationalController 对 Segue 进行单元测试
- python - Keras 一次运行多个模型的推理
- android - 如何将对象数组发送到活动