简体   繁体   中英

php array_search 0 index

It seems that that you can not use the search_array function in PHP to search the 0 index AND have it evalute as true.

Consider this code for example:

$test=array(100, 101, 102, 103);

if($key=array_search(100,$test)){

     echo $key;

}

else{

     echo "Not found";

} 

The needle '100' is found in the haystack and the key is returned as 0. So far so good, but then when I evaluate whether the search was successful or not it fails because the returned value is 0, equal to false!

The php manual suggests using '!==' but by doing so the key (array index) is not returned, instead either 1 or 0 is returned:

if($key=(array_search(103,$test)!== false)){

}

So how can I successfully search the array, find a match in the 0 index and have it evaluate as true?

This is explicitly mentioned in the docs. You need to use === or !== :

$key = array_search(...);

if ($key !== false) ...

Otherwise, when $key is 0 , which evaluates to false when tested as a boolean.

The conditional in your second example block gives execution order priority to the !== operator, you want to do the opposite though.

if (($key = array_search(100,$test)) !== false) {

!== has higher precedence than == which makes the parentheses necessary.

$key = array_search($what, $array);
if($key !== false and $array[$key] == $what) {
 return true;
}

it's more secure

if(($key = array_search(103,$test)) !== false){

}
$test=array(100, 101, 102, 103);

if (($key = array_search(100,$test)) === false) {
    echo "Not found";
} else{
    echo $key;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM