[PHP]: What does array_search() return if nothing was found?
What does array_search() return if nothing was found?
I have the need for the following logic:
$found = array_search($needle, $haystack);
if($开发者_如何学运维found){
//do stuff
} else {
//do different stuff
}
Quoting the manual page of array_search()
:
Returns the key for needle if it is found in the array,
FALSE
otherwise.
Which means you have to use something like :
$found = array_search($needle, $haystack);
if ($found !== false) {
// do stuff
// when found
} else {
// do different stuff
// when not found
}
Note I used the !==
operator, that does a type-sensitive comparison ; see Comparison Operators, Type Juggling, and Converting to boolean for more details about that ;-)
if you're just checking if the value exists, in_array is the way to go.
One has to be very careful to distinguish the cases item found with index 0
and not found
.
In the first case array_search
returns the integer 0
, in the second it returns the bool false
.
⚠ Danger zone here because if we don't pay attention, it's easy to have 0 and false
considered as the same thing in a if
test. ⚠
If you want to be able to distinguish both, you have to use if ($i !== false)
,
and not if ($i)
or if ($i != false)
. Why? See the following example:
Example:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$i = array_search('red', $array);
var_dump($i); // int(1)
echo ($i !== false) ? $i : -1; // 1
$i = array_search('blue', $array);
var_dump($i); // int(0)
echo ($i !== false) ? $i : -1; // 0 // CORRECT
echo ($i != false) ? $i : -1; // -1 // WRONG! don't use: if ($i) ...
echo ($i) ? $i : -1; // -1 // WRONG! don't use: if ($i != false) ...
$i = array_search('blueee', $array);
var_dump($i); // bool(false)
echo ($i !== false) ? $i : -1; // -1, i.e. not found
According to the official documentation at http://php.net/manual/en/function.array-search.php:
Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
See this example:
$foundKey = array_search(12345, $myArray);
if(!isset($foundKey)){
// If $myArray is null, then $foundKey will be null too.
// Do something when both $myArray and $foundKey are null.
} elseif ($foundKey===false) {
// $myArray is not null, but 12345 was not found in the $myArray array.
}else{
// 12345 was found in the $myArray array.
}
From the docs:
Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.
array_search will return FALSE if nothing is found. If it DOES find the needle it will return the array key for the needle.
More info at: http://php.net/manual/en/function.array-search.php
精彩评论