PHP Tutorial - PHP strnatcmp() Function






Definition

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

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

Syntax

PHP strnatcmp() Function has the following syntax.

strnatcmp(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

Example 1

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


<?php
echo strnatcmp("2Hello world!","10Hello world!");
echo "\n";
echo strnatcmp("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//from w w  w  .  java  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.