PHP strnatcasecmp() Function

Definition

The strnatcasecmp() function compares two strings in a natural way.

Syntax

PHP strnatcasecmp() Function has the following syntax.

strnatcasecmp(string1,string2)

Parameter

ParameterIs RequiredDescription
string1Required.First string to compare
string2Required.Second string to compare

Return

This function returns:

  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • >0 - if string1 is greater than string2

Note

In natural way, the number 2 is less than the number 10. In computer way, 10 is less than 2, because the first number in "10" is less than 2.

The strnatcasecmp() is case-insensitive.

Example 1

Compare two strings using a "natural" algorithm (case-insensitive):


<?php//  w  w w. ja v  a 2s  .c  o  m
echo strnatcasecmp("2Hello world!","10Hello WORLD!");
echo "\n";
echo strnatcasecmp("10Hello world!","2Hello WORLD!");
?>

The code above generates the following result.

Example 2

Difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp):


<?php//w ww.  j  a v a 2  s .  c om
$arr1 = $arr2 = array("PHP1","PHP2","PHP10","PHP01","PHP100","PHP20","PHP30","PHP200");
echo "Standard string comparison"."\n";
usort($arr1,"strcmp");

print_r($arr1);
echo "\n";

echo "Natural order string comparison"."\n";
usort($arr2,"strnatcmp");

print_r($arr2);
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions