Error With array_search
I seem to have hit an error with array search. Below is my code.
$allowedTypes = array(
'image/gif',
'image/jpg',
'image/jpeg',
'image/png'
);
if(array_search("image/gif", $allowedTy开发者_运维知识库pes)) {
print "true";
} else {
print "false";
}
It always prints false. Even though image/gif is in the list of allowed types.
array_search
returns the index of the item in the array. In this case, it's returning integer 0, which, when converted to bool, is false.
If you'd read the documentation, you'd have seen the following in a large red box:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
You must use:
if (array_search("image/gif", $allowedTypes) !== false) {
// ...
}
Or, to simply tell if the array contains the item, you can use in_array()
which does return a simple yes/no in boolean form:
if (in_array("image/gif", $allowedTypes)) {
// ...
}
I think this is what you are looking for:
$allowedTypes = array(
'image/gif',
'image/jpg',
'image/jpeg',
'image/png'
);
if(in_array("image/gif", $allowedTypes)) {
print "true";
} else {
print "false";
}
精彩评论