Comparing Strings

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

Comparing strings seems like an easy task use 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, too both 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.

strcmp function syntax

int strcmp ( string $str1 , string $str2 )

This function use for binary safe case sensitive string comparison and accepts two parameters:

  1. str1 first string and

  2. str2 second string

This function returns:
  • 0 if both str1 and str2 are equal

  • < 0 if str1 is less than str2

  • > 0 if str1 is greater than str2

strcasecmp function syntax

This function is identical to strcmp with one differnce, it is case incensitive.

Comparing Strings

  $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 tutorial 2, "Working with Arrays."

by BrainBellupdated