PHP strnatcmp() Function
Topic: PHP String ReferencePrev|Next
Description
The strnatcmp()
function compares two strings using a "natural order" algorithm.
This function is case-sensitive. For case-insensitive comparisons, use the strnatcasecmp()
function.
The following table summarizes the technical details of this function.
Return Value: | Returns a negative value (< 0 ) if string1 is less than string2; a positive value (> 0 ) if string1 is greater than string2, and 0 if both strings are equal. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the strnatcmp()
function is given with:
The following example shows the strnatcmp()
function in action.
Example
Run this code »<?php
// Sample strings
$str1 = "x2";
$str2 = "x11";
// Performing comparisons
echo strnatcmp($str1, $str2)."<br>";
echo strnatcmp($str2, $str1);
?>
Tip: The strnatcmp()
function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. This is described as a "natural ordering". For example, in alphabetical sorting "x11" would be ordered before "x2" because "1" is smaller than "2", but in natural sorting "x2" is ordered before "x11" because "2" is smaller than "11".
Parameters
The strnatcmp()
function accepts the following parameters.
Parameter | Description |
---|---|
string1 | Required. Specifies the first string to compare. |
string2 | Required. Specifies the second string to compare. |
More Examples
Here're some more examples showing how strnatcmp()
function actually works:
The following example demonstrates the difference between the natural order algorithm and the regular computer string sorting algorithms using this function as comparison function.
Example
Run this code »<?php
// Sample array
$images = array("img10.png", "img12.png", "img2.png", "img1.png");
// Sorting array using standard string comparison
usort($images, "strcmp");
print_r($images);
// Sorting array using natural order string comparison
usort($images, "strnatcmp");
print_r($images);
?>