PHP | strnatcmp() function

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.

Syntax:

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.

Examples:

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
    echo strnatcmp("Geek", "Geeks");
  
?>

chevron_right


Output:

-1

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
    echo strnatcmp("Geeks", "GEEks");
  
?>

chevron_right


Output:

1

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
    echo strnatcmp("Geek of month 2", "Geek of month 10");
    echo "\n";
    echo strcmp("Geek of month 2", "Geek of month 10");
  
?>

chevron_right


Output:

-1
256

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.

Reference:
http://php.net/manual/en/function.strnatcmp.php



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.