PHP array_search函数无法正确使用返回值

时间:2018-10-09 05:57:35

标签: php

今天,我发现php array_search 函数存在一个很奇怪的问题。实际上,我应用了这样的条件:如果索引为 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

2 个答案:

答案 0 :(得分:2)

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

各种类型比较

根据此表,如果将布尔值与任何其他类型进行比较,则两个值都将被转换为布尔值,然后进行比较。在您的情况下,整数0被转换为FALSE,最终php比较FALSE >= FALSE。 由于FALSEFALSE大或等于,因此您的条件返回true。

答案 1 :(得分:0)

您需要使用===,因为它会检查值并检查值的类型,以便它不会像您所遇到的那样通过条件。它正在检查值,但未检查其类型,这正在产生问题,因为它将false视为字符串,这显然是真实条件(字符串的值大于0)。

$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 === False && $output !== 0) {
    echo 'not passed'; //it should not print this condition if return value is FALSE
} else {
    echo 'passed';
}
相关问题