PHP - strnatcasecmp() Function



The PHP strnatcasecmp() function is used to compare two strings using a natural order algorithm. The "natural order algorithm" refers to a comparison method that is similar to how humans naturally sort strings containing numbers.

Following is a list of the key points about the returned value:

  • It returns 0, if both strings are equal.
  • It returns 1, if the first string is greater than the second string.
  • It returns -1, if the first string is less than the second string.

Syntax

Following is the syntax of the PHP strnatcasecmp() function −

strnatcasecmp(string $str1, string $str2): int

Parameters

This function accepts two parameters, which are listed below −

  • str1: The first string to compare.
  • str2: The second string to compare with the first.

Return Value

This function returns and an integer value (i.e., -1, 0, 1) based on comparison.

Example 1

If both strings are "equal", the PHP strnatcasecmp() function will return 0

<?php
   $str1 = "Tutorialspoint";
   $str2 = "tutorialspoint";
   echo "The given strings are: $str1, and $str2";
   echo "\nAre both the strings equal? ";
   echo strnatcasecmp($str1, $str2);
?>

Output

The above program produces the following output −

The given strings are: Tutorialspoint, and tutorialspoint
Are both the strings equal? 0

Example 2

If the first string is greater than the second string, the PHP strnatcasecmp() function will return 1

<?php
   $str1 = "World";
   $str2 = "Hello";
   echo "The given strings are: $str1, and $str2";
   $result = strnatcasecmp($str1, $str2);
   echo "\nThe function returns: $result";
   if($result == 0){
	   echo "\nStrings are equal";
   }
   else if($result == 1){
	   echo "\nFirst string is greater than second one";
   }
   else{
	   echo "\nFirst string is less than the second one";
   }
?>

Output

After executing the above program, the following output will be displayed −

The given strings are: World, and Hello
The function returns: 1
First string is greater than second one

Example 3

If the first string is less than the second string, the PHP strnatcasecmp() function will return -1

<?php
   $str1 = "Java";
   $str2 = "PHP";
   echo "The given strings are: $str1, and $str2";
   $result = strnatcasecmp($str1, $str2);
   echo "\nThe function returns: $result";
   if($result == 0){
	   echo "\nStrings are equal";
   }
   else if($result == 1){
	   echo "\nFirst string is greater than second one";
   }
   else{
	   echo "\nFirst string is less than the second one";
   }
?>

Output

Following is the output of the above program −

The given strings are: Java, and PHP
The function returns: -1
First string is less than the second one
php_function_reference.htm
Advertisements