In the manual about array_search()

Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

So if the key of array_search value is 0, it will return 0. And if the search finds no results, it could also return 0. Then how can we tell which is which? No value found, or the value found at the index 0?

Does it mean array_search also have to work with in_array to tell the difference between return index value 0 or return not found message 0?

Thanks!

    No, you're misunderstanding. If the array search returns "0", then the element is found, and it's key is "0". If it returns boolean FALSE then your search term wasn't found.

    What it's saying is that if you have the following array:

    $array = array(0=>'Windows', 1=>'Mac', 2=>'Unix', 3=>'Linux');

    And we want to see if "Windows" is in our array, it will return the key "0" which is also considered "false". But if it's not found, then it will return the boolean false, not the integer that equates to false.

      Thanks! I knew it got be my misunderstanding here.

      Basically the warning said, it could return 0 when the value found at index 0, so if we just use if (array_search(...)) to test if the return value is false would be wrong.

        Correct. Also note that using the == operator would be wrong. You need to use === so that the type is also compared. So an integer 0 loosely compared (==) to a boolean false will return true, but an integer 0 strictly compared (===) to a boolean false will return false because a boolean is not the same as an integer 😉

          Write a Reply...