note 18221 deleted from function.in-array by irc-html
| From: | irc-html@php.net | Date: | Thu, 17 Jan 2002 22:01:18 +0000 |
| Subject: | note 18221 deleted from function.in-array by irc-html | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-25000@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.