0

Finds '1' and '2' - but not zero '0'

$My_Array = array('0', '1', '2');

        if(array_search('0', $My_Array)){
            echo "FOUND";
        }else{
            echo "NOT FOUND";
        }

In this case - 0 being a string - why does it not find the zero?

6
  • 1
    0 gets casted to false Commented Jan 17, 2017 at 21:34
  • but it is a string? Commented Jan 17, 2017 at 21:35
  • yes, but it is PHP Commented Jan 17, 2017 at 21:35
  • lol... I still don't get it 0_o Commented Jan 17, 2017 at 21:38
  • PHP is weird, not much else to say Commented Jan 17, 2017 at 21:39

2 Answers 2

3

From the documentation of php.net array_search() function,

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

Now comes to your question:

why does it not find the zero?

Yes, it does find. Look at the following line,

if(array_search('0', $My_Array)){ ...

In this case array_search() function will return 0 which is the index of element '0' in the array. And because of this, the if block will get executed like this:

if(0){ ... 

which basically evaluates to false, and this means the control goes to else block even if it finds element '0' in the array.

So the solution is, change your if block in the following way:

if(array_search('0', $My_Array) !== false){ 
Sign up to request clarification or add additional context in comments.

3 Comments

Ugh!... I'm so stupid... I should have seen that :/ ... I actually was using it just like that about 10 lines down from where I had this code.... 0_o
it is returning the key [0]
I was just losing my mind until I found this answer. Thank you!
1

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

The key here is 0. if(0) results in false, hence it displays not found. PHP is doing exactly what it claims to do

Comments

Your Answer

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