Comparing Strings

PHP provides the string comparison functions strcmp( ) and strncmp( ) that safely compare two strings, str1 and str2:

strcmp and strncmp functions

strcmp and strncmp are binary safe and case sensitive string comparison functions.

integer strcmp(string str1, string str2)
//accepts two parameters

integer strncmp(string str1, string str2, integer length)
//accepts three parameters

While the equality operator == can compare two strings, the result isn't always as expected when the strings contain characters with the most significant bit set.

Both strcmp( ) and strncmp( ):

  1. take two strings as arguments, str1 and str2

  2. return 0 if the strings are identical

  3. return 1 if str1 is less than str2

  4. return -1 if str1 is greater that str2

The function strncmp( ) takes a third argument length that restricts the comparison to length characters. These examples show the results of various comparisons:

print strcmp("aardvark", "zebra");        // -1
print strcmp("zebra", "aardvark");        //  1
print strcmp("mouse", "mouse");           //  0
print strncmp("aardvark", "aardwolf", 4); //  0
print strncmp("aardvark", "aardwolf", 5); // -1

strcasecmp and strncasecmp functions

The functions strcasecmp( ) and strncasecmp( ) are case-insensitive versions of strcmp( ) and strncmp( ).

The functions strncmp( ), strcasecmp( ), or strncasecmp( ) can be used as the callback function when sorting arrays with usort( ).