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
?>
2
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) {
...
}
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)
If you only need to know if the string is in the array, but don’t need the index, use in_array()
rather than array_search()
. It returns a boolean that you can test directly with if
.
if (in_array("Mac", $array)) {
echo "OKn";
} else {
echo "Not OKn";
}