note 18221 added to function.in-array

From: Date: Tue, 15 Jan 2002 04:40:31 +0000
Subject: note 18221 added to function.in-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-24822@lists.php.net to get a copy of this message
There seems to be a gotcha with PHP 4.1 when searching for values of 0 (unquoted). the following fragment: $a = array('apple', 'orange', 'banana'); $i = 0; if (in_array_safe($i, $a)) { echo "we have a $i"; } else { echo "we don't have a $i"; } will output "we have a 0". My workaround is the following function. Note the === (three equal signs) operator in the compare. My guess is that in_array uses == (too lazy to hunt through CVS to confirm that :) ). When I tried == in my function it gave me the same error on unquoted 0. function in_array_safe($needle, $haystack) { if (is_array($haystack)) { while (list($k, $v) = each($haystack)) { if ($v === $needle) { return true; } } } return false; } Hope that saves someone a couple minutes. Regards, Patrick Bourke Oakville, ON, Canada. -- http://www.php.net/manual/en/function.in-array.php http://master.php.net/manage/user-notes.php?action=edit+18221 http://master.php.net/manage/user-notes.php?action=delete+18221 http://master.php.net/manage/user-notes.php?action=reject+18221

« previous php.notes (#24822) next »