April 24, 2012

PHP – array_search() fails on === true, but not on !== false?

Question by DaBananaboat

When I want to check if something is in the array and get the key back, I use the array_search() function.

Why is it when I compare the function to be exactly equal to true (=== true) it returns false, and when I compare it to not be exactly equal to false (!== false) it returns true?

<?php
    if(array_search($value, $array) === true)
    {
        // Fails
    }

    if(array_search($value, $array) !== false)
    {
        // Succeeds
    }
?>

Thanks in advance.

Answer by Starx

array_search() does not return true.

If will only return false, if it can’t find anything, otherwise it will return the key of the matched element.

According to the manual

array_search — Searches the array for a given value and returns the corresponding key if successful
….

Returns the key for needle if it is found in the array, FALSE otherwise.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!