Home > Mobile >  Why array_search does not recognize first item in array?
Why array_search does not recognize first item in array?

Time:12-08

I am confused. Why does array_search skip the first element in an array? in_array returns only booleans, array_search can return any values - is its because of that? For now it makes no sense to me. Sample code below:

<?php

$array = array("Mac", "NT", "Linux");

if (in_array("Mac", $array)) {
    echo "Ok \n";
} else {
    echo "Not ok \n";
}
// output: Ok

if (array_search("Mac", $array)){
     echo "Ok \n";
} else {
    echo "Not ok \n";
}
// output: Not Ok

$arrayForArraySearch = array('', "Mac", "NT", "Linux"); // add first element

if (array_search("Mac", $arrayForArraySearch)){
     echo "Ok \n";
} else {
    echo "Not ok \n";
}
// output: Ok, but it's no longer first item
?>

CodePudding user response:

It's because array_search is returning 0 which is the index of "Mac" in the array. If the item is not found in the array, it will return false.

Always compare the result to false:

if (array_search("Mac", $array) !== false) {
...
}

CodePudding user response:

As in the docs of the array_search function is mentioned, the key of the found element is returned. With your if condition this results in false, because the key of your element "Mac" is 0.

Change your condition to match not false => if (array_search("Mac", $array) !== false)

  • Related