PHP Tutorial - PHP strcmp() Function






Definition

The strcmp() function, and its case-insensitive sibling, strcasecmp(), is a quick way of comparing two words.

Syntax

PHP strcmp() Function has the following syntax.

int strcmp ( string str1, string str2 )

Parameter

PHP strcmp() Function takes two words for its two parameters

Return

PHP strcmp() Function returns

  • -1 if word one comes alphabetically before word two,
  • 1 if word one comes alphabetically after word two, or
  • 0 if word one and word two are the same.




Example


<?PHP/*from  w w w .j av  a  2 s .c  om*/
$string1 = "java"; 
$string2 = "php"; 
$result = strcmp($string1, $string2); 

switch ($result) { 
        case -1: print "string1 comes before string2"; break; 
        case 0: print "string1 and string2 are the same"; break; 
        case 1: print "string1 comes after string2"; break; 
} 
?>

Capital letters come before their lowercase equivalents. For example, "PHP" will come before "php."

The code above generates the following result.