Re: in_array breaks down for 0 as value

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2008/11/19 Yashesh Bhatia <yasheshb@xxxxxxxxx>:
> Hi.
>
>  I wanted to use in_array to verify the results of a form submission
> for a checkbox and found an interesting
> behaviour.
>
> $ php -v
> PHP 5.2.5 (cli) (built: Jan 12 2008 14:54:37)
> $
>
> $ cat in_array2.php
> <?php
> $node_review_types = array(
>                           'page'       => 'page',
>                           'story'      => 'story',
>                           'nodereview' => 'abc',
>                           );
>
> if (in_array('page', $node_review_types)) {
>  print "page found in node_review_types\n";
>  }
> if (in_array('nodereview', $node_review_types)) {
>  print "nodereview found in node_review_types\n";
>  }
>
> ?>
> $ php in_array2.php
> page found in node_review_types
> $
>
> This  works fine. but if i change the value of the key 'nodereview' to
> 0 it breaks down.
>
> $ diff in_array2.php in_array3.php
> 6c6
> <                            'nodereview' => 'abc',
> ---
>>                            'nodereview' => 0,
> $
>
> $ php in_array3.php
> page found in node_review_types
> nodereview found in node_review_types
> $
>
> Any reason why in_array is returning TRUE when one has a 0 value on the array ?
>
> Thanks.

Hi Yasheed,

It looks like you've found the reason for the existence of the
optional third argument to in_array(): 'strict'. In your second
example (in_array3.php), what happens is that the value of
$node_review_types['nodereview'] is 0 (an integer), so it is compared
against the integer value of the first argument to in_array(), which
is also 0 (in PHP, the integer value of a string with no leading
numerals is 0). In other words, in_array() first looks at the first
element of $node_review_types and finds that it is a string, so it
compares that value as a string against the string value of its first
argument ('nodereview'). Same goes for the second element of
$node_review_types. However, when it comes time to check the third
element, in_array() sees that it is an integer (0) and thus compares
it against the integer value of 'nodereview' (also 0), and returns
true.

Make any sense? The problem goes away if you give a true value as the
third argument to in_array(): this tells it to check the elements of
the given array for type as well as value--i.e., it tells in_array()
to not automatically cast the value being searched for to the type of
the array element being checked.


Torben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux