Jump to: navigation, search

Php strnatcmp

From w3cyberlearnings

Contents

PHP function strnatcmp

This function compares two strings by using a natural algorithm. (Natural algorithm is a human readable form of comparsion). This function is case sensitive.

Syntax strnatcmp

  • string1: string input 1
  • string2: string input 2
strnatcmp(string1,string2);

Return

  • 0: when two string equal.
  • >0: string1 is greater than string2.
  • <0: string2 is greater than string1.

Natural Algorithm

1 is less than 2, and 3 is less than 10.

  • Disorder List: 1,12,11,2,40,20
  • Computer ways of understand the number order:1,11,12,2,20,40
  • Natural Algorithm:1,2,11,12,20,40

Example 1

<?php

$str1 = 'a100pple';
$str2 = 'a2apple';
echo strnatcmp($str1, $str2);
?>


Output: First string is larger than the second string

1

Example 2

<?php

$aaf1 = $aaf2 = array(
	 'File1',
	 'File2',
	 'File10',
	 'File01',
	 'File100',
	 'File21',
	 'File31'
);

echo "Standard string comparison\n";
usort($aaf1, "strcmp");

print_r($aaf1);

echo "\nNatural order string comparison\n";
usort($aaf2, "strnatcmp");

print_r($aaf2);
?>

Output

Standard string comparison
Array
(
    [0] => File01
    [1] => File1
    [2] => File10
    [3] => File100
    [4] => File2
    [5] => File21
    [6] => File31
)

Natural order string comparison
Array
(
    [0] => File01
    [1] => File1
    [2] => File2
    [3] => File10
    [4] => File21
    [5] => File31
    [6] => File100
)


Related Functions


Navigation
Web
SQL
MISC
References