note 75117 added to language.operators.comparison
| From: | hg at ecs dot soton dot ac dot uk | Date: | Sun, 13 May 2007 12:12:51 +0000 |
| Subject: | note 75117 added to language.operators.comparison | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126476@lists.php.net to get a copy of this message | ||
Warning, string comparison may be even stranger than you thought:
<?php
$a = "0e2";
$b = "0e3";
if ($a == $b) print '$a == $b'."\n"; // True
if ($a === $b) print '$a === $b'."\n"; // False
if ("000e002073" == "0e2857") print '"000e002073" ==
"0e2857"'."\n"; // True
?>
outputs
$a == $b
"000e002073" == "0e2857"
According to Table 15.4, since $a and $b are of the same type, it might have been expected that ==
and === gave the same result? Not necessarily.
The clue is in the text below the table:
"If you compare two numerical strings, they are compared as integers."
Since these strings are numerical strings (in fact floats, if you hadn't worked it out yet),
they are compared as integers.
This is the behaviour we know and love about php, and I have no problem with it. I do have a problem
that == and === give different answers for objects when "they are of the same type."
I think that Table 15.4 gives no inkling of this.
Table 15.5 might have made the situation clearer, but makes no distinction between == and ===.
Of course, to be really safe, we should have been using strcmp() in any case, but it seems to be
quite common that people use == for strings, so it should be pointed out.
I am suggesting (by other mechanism) a change to the page, but in the meantime (or if it is
rejected) this note may help.
By the way, this was a real problem for me.
If you are comparing a significant number of strings which happen to be hex, it is quite surprising
to find that "000" == "0e0" whereas "000" != "0f0".
I think I might start using things like "0e0" for username and password on websites to see
what breaks :-)
----
Server IP: 69.147.83.197
Probable Submitter: 213.78.201.121
----
Manual Page -- http://www.php.net/manual/en/language.operators.comparison.php
Edit -- https://master.php.net/note/edit/75117
Del: integrated -- https://master.php.net/note/delete/75117/integrated
Del: useless -- https://master.php.net/note/delete/75117/useless
Del: bad code -- https://master.php.net/note/delete/75117/bad+code
Del: spam -- https://master.php.net/note/delete/75117/spam
Del: non-english -- https://master.php.net/note/delete/75117/non-english
Del: in docs -- https://master.php.net/note/delete/75117/in+docs
Del: other reasons-- https://master.php.net/note/delete/75117
Reject -- https://master.php.net/note/reject/75117
Search -- https://master.php.net/manage/user-notes.php