PHP strnatcasecmp() Function
Topic: PHP String ReferencePrev|Next
Description
The strnatcasecmp()
function compares two strings using a "natural order" algorithm.
This function is case-insensitive. For case-sensitive comparisons, use the strnatcmp()
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 strnatcasecmp()
function is given with:
The following example shows the strnatcasecmp()
function in action.
Example
Run this code »<?php
// Sample strings
$str1 = "x2";
$str2 = "X11";
// Performing comparisons
echo strnatcasecmp($str1, $str2)."<br>";
echo strnatcasecmp($str2, $str1);
?>
Tip: The strnatcasecmp()
function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. This is described as a "natural ordering", e.g., in alphabetical sorting "x11" will 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 strnatcasecmp()
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 strnatcasecmp()
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, "strnatcasecmp");
print_r($images);
?>