Skip to content
Related Articles

Related Articles

PHP | strnatcmp() function

View Discussion
Improve Article
Save Article
  • Last Updated : 06 Apr, 2018

The strnatcmp() is a built-in function on PHP. This function compares two strings using a “natural order” algorithm and return a positive integer, negative or zero. This function is case-sensitive.


strnatcmp( $string1, $string2 )

Parameters: The functions accepts two mandatory string parameters for comparison as shown in the above syntax.

  • $string1: This parameter specifies the first string to compare.
  • $string 2: This parameter specifies the first string to compare.

Return Value: This function returns an integer value based on the following criteria:

  • The function returns 0 if both the strings are equal.
  • The function returns a negative value(<0) if $string1 is less than $string2.
  • The function returns a positive value(>0) if $string2 is less than $string1.


Input : $string1 = "Hello", $string2 = "HEllo"
Output : 1

Input : $string1 = "Geek", $string2 = "Geeks"
Output : -1

Below programs illustrate the strnatcmp() function in PHP :

Program 1: This program shows simple use of the strnatcmp() function.

    echo strnatcmp("Geek", "Geeks");



Program 2: This program shows case-sensitivity of the strnatcmp() function.

    echo strnatcmp("Geeks", "GEEks");



Program 3: This program illustrates the difference between strcmp() and strnatcmp() functions.

    echo strnatcmp("Geek of month 2", "Geek of month 10");
    echo "\n";
    echo strcmp("Geek of month 2", "Geek of month 10");



Explanation : In a natural algorithm, the number 2 is less than the number 10 whereas in computer sorting, 10 is considered to be less than 2 as the first number in “10” is less than 2.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!