John Davidson

php - Why array_search does not recognize first item in array?

0 comments
Message:


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
?>


My Answer:
php
$fruits = array("apple", "banana", "cherry");

$key = array_search("apple", $fruits);

echo $key; // Output: 1


In the above code, `array_search` is correctly recognizing the first item in the array as "apple" and returning the key `1`.

If `array_search` is not recognizing the first element in your array, there may be an issue with the data or the way you are using the function. Make sure that the value you are searching for is actually present in the array and that you are using the function correctly.

Rate this post

4 of 5 based on 5989 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us