Re: strcmp($var1, $var2) versus if ($var1 < $var2)
| From: | C.R.Vegelin | Date: | Wed, 28 May 2008 12:30:17 +0000 |
| Subject: | Re: strcmp($var1, $var2) versus if ($var1 < $var2) | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-274764@lists.php.net to get a copy of this message | ||
----- Original Message ----- From: "David Otton" <phpmail@jawbone.freeserve.co.uk>
To: "C.R.Vegelin" <cr.vegelin@hetnet.nl>
Cc: "php-general@lists.php.nt" <php-general@lists.php.net>
Sent: Wednesday, May 28, 2008 12:11 PM
Subject: Re: [PHP] strcmp($var1, $var2) versus if ($var1 < $var2)
2008/5/28 C.R.Vegelin <cr.vegelin@hetnet.nl>:Hi David, I already suspected that the > operator forced a numeric comparison. Even if I use: if ((string) $var1 < (string) $var2) ... So I have to use strcmp() Thanks, Cor$var1 = "01011090"; $var2 = "010190"; // 2 strings if ($var1 < $var2) ECHO "var1 < var2"; else ECHO "var1 >= var2"; echo "<br />"; $r = strcmp ( $var1 , $var2 ); if ($r < 0) ECHO "var1 < var2", "<br />"; 2nd line says: $var1 >= $var2 4th line says: $var1 < $var2Implicit type conversion. "<" is a numeric operator, so your strings are silently promoted to integers, where (1011090 > 10190). strcmp() treats the strings as strings, and orders them in something close to ASCII order (which isn't the same as alphabetical ordering, BTW, and see the comments at www.php.net/strcmp for locale-specific gotchas). PHP's implicit conversions can bite you if you don't understand them. Try this one: $a = 'string'; $b = 0; if ($a==true && $b==false && $a==$b) { echo ('universe broken'); }