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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



----- Original Message ----- From: "David Otton" <phpmail@xxxxxxxxxxxxxxxxxxxxxxx>
To: "C.R.Vegelin" <cr.vegelin@xxxxxxxxx>
Cc: "php-general@xxxxxxxxxxxx" <php-general@xxxxxxxxxxxxx>
Sent: Wednesday, May 28, 2008 12:11 PM
Subject: Re:  strcmp($var1, $var2) versus if ($var1 < $var2)


2008/5/28 C.R.Vegelin <cr.vegelin@xxxxxxxxx>:

$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');
}


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





--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux