Reputation: 7530
I'm having trouble understanding the result of array_search in the following example (and did not find any existing questions discussing this):
<?php
$values = array(
15,
12,
"15",
34,
15 => 25,
"xx" => 15
);
echo "PHP-Version is " . phpversion();
echo "<h1>Array:</h1><pre>";var_dump($values);echo "</pre>";
// sort($values); // remove comment and 15 will be found in ALL cases!
$key = array_search("15",$values);
show_result('(a) Searching "15"');
$key = array_search("15",$values,true);
show_result('(b) Searching "15",true');
$key = array_search(15,$values);
show_result('(c) Searching 15');
$key = array_search(15,$values,false);
show_result('(d) Searching 15,false');
$key = array_search(15,$values,true);
show_result('(e) Searching 15,true');
function show_result($tit) {
global $key,$values;
echo "<h2>$tit</h2>";
if (!$key) {
echo "Not found";
} else {
echo "Found key $key - " . gettype($values[$key]);
}
}
?>
Only search (b) - the strict string-search finds the value, numeric search does not find it. All searches do find it when the array is sorted - but the doc does not mention such a requirement at all. Can someone explain this behaviour?
Upvotes: 2
Views: 285
Reputation: 15711
Here's the total explaination:
In all your cases, $key equals to 0, and since you are doing a simple test like if($key)
0 evaluates to false making you think that the search was not succesful. Changing it to if($key===false)
will work without any problem.
The reason why it works without any problem when you sort the array is because the value 12 is inside so it takes the key 0 and the 15 that was at key 0 is now at key 1 and 1 evaluates to true
.
Upvotes: 1
Reputation: 30071
I think this is because the return value of array_search
is a mixed value. When you perform the first search it will find the value at position 0
and therefor return the keys index which in turn will be evaluated to false
.
Upvotes: 1
Reputation: 522382
The value 15
is at key 0
. array_search
returns this 0
. 0
evaluates to false
. Your check if (!$key)
therefore fails for the key 0
. You have to check for strict === false
. There's a giant red warning in the manual explaining this.
Upvotes: 4