Re: strcmp($var1, $var2) versus if ($var1 < $var2)

From: Date: Wed, 28 May 2008 11:11:13 +0000
Subject: Re: strcmp($var1, $var2) versus if ($var1 < $var2)
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-274763@lists.php.net to get a copy of this message
2008/5/28 C.R.Vegelin <cr.vegelin@hetnet.nl>: > $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 < $var2 Implicit 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'); }

« previous php.general (#274763) next »