Open In App

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.

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



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.




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

Output:

-1

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




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

Output:

1

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




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

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


Article Tags :