11

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?

2
  • Did you not see the BIG RED BOX? Try to read the documentation and understand the language before you ask such questions. Commented Apr 10, 2013 at 19:16
  • This is just bad and lazy code. Why do you need to test and get in the same if ? Commented Aug 30, 2024 at 11:27

5 Answers 5

46

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You could of course use if( ($key = array_search(...)) !== false)
I read several threads on this, read the manual over and over but couldn't find the answer. I think I had the '!==' in the wrong part of my code. Now working - thanks!
but in this manner if I use code like if(array_search(...) === true), then why it is not working. (=== true is also string comparison) can anybody explain me
@EstailSe Your code makes no sense. array_search can never return boolean true, so no, it will not work, and it's not clear what you're trying to accomplish.
okay I got your point! thanks, I was comparing index number with Boolean, there I was wrong!
5

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.

1 Comment

Note: This is the most correct in here. If I could transfer the upvotes from my awful, old, naive, now-deleted answer I would.
1
$key = array_search($what, $array);
if($key !== false and $array[$key] == $what) {
 return true;
}

it's more secure

Comments

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

}

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.