On 20 Nov 2008, at 06:55, Yashesh Bhatia wrote:
 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 ?

That's weird, 5.2.6 does the same thing. There's actually a comment about this on the in_array manual page from james dot ellis at gmail dot com...

<quote>

Be aware of oddities when dealing with 0 (zero) values in an array...

This script:
<?php
$array = array('testing',0,'name');
var_dump($array);
//this will return true
var_dump(in_array('foo', $array));
//this will return false
var_dump(in_array('foo', $array, TRUE));
?>

It seems in non strict mode, the 0 value in the array is evaluating to boolean FALSE and in_array returns TRUE. Use strict mode to work around this peculiarity. This only seems to occur when there is an integer 0 in the array. A string '0' will return FALSE for the first test above (at least in 5.2.6).

</quote>

So use strict mode and this problem will go away. Oh, and please read the manual before asking a question in future.

-Stut

--
http://stut.net/

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

Reply via email to