Re: note 8952 added to Comparison Operators
| From: | Lars Torben Wilson | Date: | Sun, 08 Oct 2000 23:47:51 +0000 |
| Subject: | Re: note 8952 added to Comparison Operators | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-6223@lists.php.net to get a copy of this message | ||
johan@essay.org writes:
> $cool = 0;
> if($cool == "a"){
> echo "if(cool) == true\n";
> }
>
> Howcome this test actually returns TRUE ?? Isb't this a bug ?
>
> http://www.php.net/manual/language.operators.comparison.php
First, this note has been deleted; the place for discussion about PHP
is the general mailing list at php-general@lists.php.net; the place
for bug reports is the bug database at http://bugs.php.net. Please
make sure to read the instructions at
http://www.php.net/manual/add-note.php before
adding another note.
As to the question, the above is not a bug; it is the expected
behaviour. For an in-depth explanation, read:
http://www.php.net/manual/language.types.type-juggling.php
http://www.php.net/manual/language.types.string.php#language.types.string.conversion
(The above links may get wrapped by mailing; sorry about that.)
Anyway, the short answer is that what's going on is PHP's type
conversion rules. Since you are comparing an integer ($cool, with the
value 0) and a string ("a"), the string gets compared as an
integer, meaning that PHP converts "a" to an integer for the
comparison. In other words, the line:
if ($cool == "a") {
...is interpreted as:
if ($cool == (int) "a") {
...which, since converting "a" to an integer results in the value 0,
evaluates as true.
In PHP 4, there is another equality operator: ===, meaning "identical
to". This operator compares both the values and the types of its
operands, so that the following:
if ($cool === "a") {
...would evaluate as false, since although $cool and "a" have the same
integer value, they are of different types.
Another way which doesn't require the === operator would be to force
the types to compare as you are expecting:
if ((string) $cool == "a") {
Hope this helps explain it,
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|
+----------------------------------------------------------------+