34

I was trying to understand the in_array behavior at the next scenario:

$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey');
var_dump(in_array(0, $arr));

The returned value of the in_array() is boolean true. As you can see there is no value equal to 0, so if can some one please help me understand why does the function return true?

2
  • 2
    I see two entries equal to 0 in this array Dec 12, 2012 at 19:05
  • Hey Jonathan, Thank you for your answer realy good one, thanks again and have a nice day. Dec 12, 2012 at 19:32

5 Answers 5

70

This is a known issue, per the comments in the documentation. Consider the following examples:

in_array(0, array(42));      // FALSE
in_array(0, array('42'));    // FALSE
in_array(0, array('Foo'));   // TRUE

To avoid this, provide the third paramter, true, placing the comparison in strict mode which will not only compare values, but types as well:

var_dump(in_array(0, $arr, true));

Other work-arounds exist that don't necessitate every check being placed in strict-mode:

in_array($value, $my_array, empty($value) && $value !== '0');

But Why?

The reason behind all of this is likely string-to-number conversions. If we attempt to get a number from "Bye", we are given 0, which is the value we're asking to look-up.

echo intval("Bye"); // 0

To confirm this, we can use array_search to find the key that is associated with the matching value:

$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey');
echo array_search(0, $arr);

In this, the returned key is 2, meaning 0 is being found in the conversion of Bye to an integer.

5
  • 3
    This answer would be better if it explained why PHP evaluates 0 == 'string' to TRUE
    – ernie
    Dec 12, 2012 at 19:08
  • Yeah, I just wasn't sure why either . . . I posted my experiments/conclusions in my answer, as well as the specific line about strings being converted to 0, but thanks for your clarification.
    – ernie
    Dec 12, 2012 at 19:17
  • @ernie Nice work. I figured the natural thing would be to leverage array_search to see which value PHP is finding to be equal to 0, and sure enough it's the first string that doesn't start with an number in it.
    – Sampson
    Dec 12, 2012 at 19:31
  • Definitely a fun little question - didn't realize that strings were generally converted to 0 during type juggling, and that loose string/number comparisons would default to numeric comparisons.
    – ernie
    Dec 12, 2012 at 19:32
  • 2
    @ernie A string of '4u' would be converted to 4 after juggling. But if the first character is not a number, it will be converted to 0 instead. Definitely a fun question.
    – Sampson
    Dec 12, 2012 at 19:42
10

Try adding a third parameter true (strict mode) to your in_array call.

4

This is a result of the loose comparison and type juggling.

Loose comparison means that PHP is using == not === when comparing elements. == does not compare that the two variable types are equal, only their value, while === will ensure that they match in type and value (e.g. compare 0 == FALSE and 0 === FALSE).

So, basically, your in_array function is checking:

0 == 'Bye'
0 == 'Hey'
0 == 77

Note that the 52 will get lost due to the way you created your array.

So, note that if you do:

print (0 == 'Bye');

You will get 1. Apparently, PHP is type juggling the 'Bye' to 0, which is the same thing that will happen when you cast a string to an int, e.g. (int) 'string' will equal 0. Specific reference from the String conversion to numbers doc (Emphasis added):

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

Apparently, the integer type takes precedence over the string type (i.e. it could just as easily be doing the comparison by casting the int 0 to a string, which would then return False). This is specified in the comparison operators doc:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

Thanks for an interesting question that led me to do some research and learn something new!

1
  • Thank you for the full explanation. I just ran into the problem of this post and could not figure out why PHP was doing what it is doing. Not sure how I am going to remember this as this feels really contrary to how PHP works. But having your full explanation gives my brain a fighting chance to 'vaguely recall' such errors. Thank you for taking the time to do the research to figure this all out!
    – David M
    Sep 22, 2014 at 21:05
1

in_array is supposed to be used on indexed arrays ([0], [1], [2] etc), not with a dictionary as you have defined (key-value store).

If you want to check if your array $arr includes '0', try using the PHP function array_key_exists instead - http://php.net/manual/en/function.array-key-exists.php.

var_dump(array_key_exists(0, $arr));
1
  • 2
    in_array has no limitation on whether the array is indexed or not; all it does is check if the values in the array (indexed or hashed) match the needle.
    – ernie
    Dec 12, 2012 at 19:23
0

Type compare (third parameter) needs more system resources and more time. Simply do that:

$x=0;
$result=in_array($x.'',array('ABC','BAC','12c','54'));
var_dump($result);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.