Wednesday, November 20, 2024
Google search engine
HomeLanguagesPHP strnatcmp() function

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.




<?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

RELATED ARTICLES

Most Popular

Recent Comments