1

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", $allowedTypes)) {
    print "true";
} else {
    print "false";
}

It always prints false. Even though image/gif is in the list of allowed types.

0

2 Answers 2

6

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)) {
  // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah ha! Makes perfect sense. I've used in_array() anyway, it seems to be a more logical function for this purpose. Thanks
2

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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.