Kuldeep Singh Potiwal
Kuldeep Singh Potiwal

Reputation: 291

PHP array_search function not working properly with return values

Today, I found a quite weird issue with php array_search function. Actually I applied the condition that, if index is 0 or greater than it should passed the IF condition otherwise not but its not functioning like that.

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 ?

It seems like not array_search function issue but i faced when using this function.

$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 Manual : http://php.net/manual/en/function.array-search.php

Upvotes: 4

Views: 1528

Answers (2)

Arthur Shveida
Arthur Shveida

Reputation: 457

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 ?

Take a look at Comparison with Various Types table at http://php.net/manual/en/language.operators.comparison.php

According to this table, if you compare boolean with any other type, both values are converted to boolean and then compared. In your case integer 0 is converted to FALSE and eventually php compares FALSE >= FALSE. Since FALSE is greater or equal to FALSE you condition returns true.

Upvotes: 2

Exterminator
Exterminator

Reputation: 1246

You need to use === as it checks the value and also checks for the type of the value so that it won't pass the condition as it was happening in your case. It was checking for the value but wasn't checking its type which was creating the problem as it was treating false as a string which is obviously true condition (value of string is greater than 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';
}

Upvotes: 0

Related Questions