strnatcmp – PHP String Functions

Syntax :

int strnatcmp ( string1, string2 );

Description :

It’s an inbuilt function of PHP. strnatcmp() function compares the two strings  using a “natural” algorithm.

Note: This function is  binary-safe and case-sensitive.

Parameter :

[table caption=”” width=”100%” colwidth=”15%|15%|15%|55%” colalign=”left|left|left|left”]
Name, Required /Optional, Value Type, Description

string1, Required, String, First string to compare.

string2, Required, String, Second string to compare.

[/table]


Output :

Return values in this function are:

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

Related articles : strcmp()strcasecmp()substr()stristr()strncasecmp(), strncmp()strstr(), natsort(), natcasesort().


strnatcmp() – PHP Functions Example 1 :
<?php
// case-sensitive comparison
echo strnatcmp("Hi from tutorialmines.","hI FROM TUTORIALMINES."); 
?>

Output of above code in the browser is as below:

-1

strnatcmp() – PHP Functions Example 2 : It returns 0, if the two strings are equal. Case of character does matter here.
<?php
echo strnatcmp("Hi from tutorialmines.","Hi from tutorialmines.");
echo "<br/>";
echo strnatcmp("Hi tutorialmines.","hI from Tutorialmines.");
?>

Output of above code in the browser is as below:

0
-1

strnatcmp () – PHP Functions Example 3 :
<?php
echo "String1 is equal to string2 = ";
echo strnatcmp("Hi from tutorialmines.","Hi from tutorialmines.");
echo "\nString1 is less than string2 = ";
echo strnatcmp("Hi from tutorial.","Hi from tutorialmines.");
echo "\nString1 is greater than string2 = ";
echo strnatcmp("Hi from tutorialmines.","Hi from tutorial.");
?>

Output of above code in the browser is as below:

String1 is equal to string2 = 0
String1 is less than string2 = -1
String1 is greater than string2 = 1

strnatcmp () – PHP Functions Example 4 : difference between this algorithm and the regular computer string sorting algorithms can be seen below:
<?php
$arr1 = $arr2 = array("var12", "var10", "var2", "var1");
echo "Standard string comparison\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?>

Output of above code in the browser is as below:

Standard string comparison
Array
(
[0] => var1
[1] => var10
[2] => var12
[3] => var2
)

Natural order string comparison
Array
(
[0] => var1
[1] => var2
[2] => var10
[3] => var12
)

You may also like...