Latest web development tutorials

PHP strnatcasecmp () function

PHP String Reference PHP String Reference

Examples

Using "natural" algorithm to compare two strings (case insensitive):

<?php
echo strnatcasecmp("2Hello world!","10Hello WORLD!");
echo "<br>";
echo strnatcasecmp("10Hello world!","2Hello WORLD!");
?>

Running instance »

Definition and Usage

strnatcasecmp () function uses a "natural" algorithm to compare two strings (case insensitive).

Natural algorithm, the number is smaller than the number 10. In the computer ordering, 10 is less than 2, because 10 is the first number in less than 2.

Note: strnatcasecmp () is case-insensitive.


grammar

strnatcasecmp( string1,string2 )

参数 描述
string1 必需。规定要比较的第一个字符串。
string2 必需。规定要比较的第二个字符串。

technical details

return value: This function returns:
  • 0 - if the two strings are equal
  • <0 - if string1 is less than string2
  • > 0 - if string1 is greater than string2
PHP version: 4+


More examples

Example 1

Nature algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp) are different:

<?php
$arr1 = $arr2 = array("pic1","pic2","pic10","pic01","pic100","pic20","pic30","pic200");
echo "Standard string comparison"."<br>";
usort($arr1,"strcmp");

print_r($arr1);
echo "<br>";

echo "Natural order string comparison"."<br>";
usort($arr2,"strnatcmp");

print_r($arr2);
?>

Running instance »


PHP String Reference PHP String Reference