# why does in_array return true

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
hello all

I must be missing something obvious, but, given:

var \$haystack = array(0);
var \$needle = '0_50';

why does:

in_array(\$needle,\$haystack)  return true?

(PHP Version 5.2.4-2ubuntu5.10)

thanks.

## Re: why does in_array return true

On 9/28/2010 9:24 PM, heartmeat wrote:

Because 0 is an integer and 0_50 is a string.  See

http://www.php.net/manual/en/language.types.type-juggling.php

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

## Re: why does in_array return true

This does not even parse. Unexpected 'var'.

Assuming what you meant is

\$haystack = array(0);
\$needle = '0_50';

then think about what in_array is doing internally. It's comparing the value
of \$needle with each element of the array \$haystack looking for a match.
It's a bit like

for (\$i = 0; \$i < count(\$haystack); \$i++)
{
if (\$needle == \$haystack[\$i])
return true;
}
return false;

Now, what is the result of (\$needle == \$haystack[0]) ?. True of course.

\$haystack[0] is a number, so the comparison will cause \$needle to be
converted to a number, along the lines of intval(\$needle). Now, \$needle is
"0_50" and intval(\$needle) is, of course, 0. If \$needle was "1_50" then
intval(\$needle) would be 1.

Did you perchance forget to include the third parameter of in_array, bool
\$strict ? If you had then the above comparison would have been
if (\$needle === \$haystack[\$i])
which of course false whenr \$i is 0 as \$needle and \$haystack[0] are of
different type.

## Re: why does in_array return true

On 29/09/10 02:24, heartmeat wrote:

You didn't specify strict checking, so the string equates to 0.

Rgds

Denis McMahon

## Re: why does in_array return true

On Tue, 28 Sep 2010 18:24:58 -0700 (PDT), heartmeat

var is not used in PHP.  Some confusion with JavaScript?

Are you perhaps expecting array(0) to give you and empty array?  It
doesn't, it gives you an array with one element.

An empty array would be:
\$haystack = array();