MisterBla
MisterBla

Reputation: 2395

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

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.

Upvotes: 2

Views: 8538

Answers (4)

random_user_name
random_user_name

Reputation: 26170

Late to the party, but wanted to add some context / examples:

array_search will return the key (if the value is found) - which could be 0 - and will return FALSE if the value is not found. It never returns TRUE.

This code may sum it up better:

// test array...
$array = [
    0   => 'First Item',
    1   => 'Second Item',
    'x' => 'Associative Item'
];

// example results:
$key = array_search( 'First Item', $array );       // returns 0
$key = array_search( 'Second Item', $array );      // returns 1
$key = array_search( 'Associative Item', $array ); // returns 'x'
$key = array_search( 'Third Item', $array );       // returns FALSE

Since 0 is a falsey value, you wouldn't want to do something like if ( ! array_search(...) ) {... because it would fail on 0 index items.

Therefore, the way to use it is something like:

$key = array_search( 'Third Item', $array ); // returns FALSE
if ( FALSE !== $key ) {
    // item was found, key is in $index, do something here...
}

It's worth mentioning this is also true of functions like strpos and stripos, so it's a good pattern to get in the habit of following.

Upvotes: 4

Starx
Starx

Reputation: 79021

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.

Upvotes: 0

allen213
allen213

Reputation: 2277

It will fail because if the call is succesfull it returns the key no true.

false is returned if it isnt found so === false is ok

from the manual:

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

Upvotes: 0

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35146

array_search returns you needle when a match is found. it returns false only when match is not found. This is why only the opposite works in your case.

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

Upvotes: 10

Related Questions