首页 > 解决方案 > 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

标签: 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。


推荐阅读