Re: is this a bug in PHP4?
| From: | Lars Torben Wilson | Date: | Thu, 21 Dec 2000 06:27:25 +0000 |
| Subject: | Re: is this a bug in PHP4? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-31334@lists.php.net to get a copy of this message | ||
phpmail@intranet.alpsnet.com writes:
>
> <?
> $var = 0;
> echo "--$var--<br>";
> if($var == "am") echo "var == am is true";
> else echo "var == am is false";
> ?>
>
> If you run that on PHP 4.0 or PHP 4.0.3pl1 you will see that
>
> if($var == "am") evaluates to TRUE
>
> This looks like a bug because I just set $var to zero.
>
> zero != "am", right?
Nope. It's a bit weird at first, but 0 does, indeed, == "am". You want
to use '==='. An explanation is given here:
http://www.php.net/manual/language.types.string.php#language.types.string.conversion
(That link might wrap in your mail program.)
I don't have a lot of time right now, but basically it happens
because in the case above, "am" gets converted to int for the purpose
of the comparison. When converting a string to int, the int value
becomes the value of any digits before the first non-digit character
in the string. So "23am" becomes 23, "4f7oo" becomes 4, and so
forth. Since the string "am" doesn't have any digits before the 'a',
it evaluates to 0, and thus 0 == "am" (really, 0 == 0) evaluates as
true.
Use '===', which makes sure that a) variables are equal, and b) they
are of the same type.
Hope this helps,
Torben
--
+----------------------------------------------------------------+
|Torben Wilson <torben@php.net> Netmill iTech|
|http://www.coastnet.com/~torben http://www.netmill.fi|
|Ph: 1 250 383-9735 torben@netmill.fi|
+----------------------------------------------------------------+