Comparing Strings


 strcmp($a, $b) strcasecmp($a, $b) 


Comparing strings seems like an easy taskuse the == operator for implicit type conversion (so '1' == 1 returns true) or the === operator for type checking (so '1' === 1 returns false). However, the first method is rather flawed because the type conversions are not always turned into strings. For instance, 1 == '1twothree' returns TRue, tooboth values are converted into integers. Therefore, === is the way to go.

However, PHP also offers functions that offer a bit more than just comparing strings and returning true or false. Instead, strcmp() returns a positive value when the string passed as the first parameter is greater than the second parameter, and a negative value when it is smaller. If both strings are equal, strcmp() returns 0. If no case sensitivity is required, strcasecmp() comes into play. It works as strcmp(); however, it does not distinguish between uppercase and lowercase letters.

Comparing Strings (compare.php)
 <?php   $a = 'PHP';   $b = 'php';   echo 'strcmp(): ' . strcmp($a, $b) . '<br />';   echo 'strcasecmp(): ' . strcasecmp($a, $b); ?> 

Which outputs:

 strcmp(): -1 strcasecmp(): 0 

These two functions can be used to sort arrays. More about custom array sorting can be found in Chapter 2, "Working with Arrays."




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net