note 75117 deleted from language.operators.comparison by danbrown

From: Date: Thu, 18 Jun 2009 14:04:48 +0000
Subject: note 75117 deleted from language.operators.comparison by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-157067@lists.php.net to get a copy of this message
Note Submitter: hg at ecs dot soton dot ac dot uk ---- 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 :-)

« previous php.notes (#157067) next »