In PHP, strnatcasecmp() compares two strings using natural order, ignoring case.
Natural order means numbers inside text are compared by value, so "file2" comes before "file10", the way people expect.
Syntax
Call strnatcasecmp() with the values you need. Start with this line.
PHP
$result = strnatcasecmp("File2", "file10");
Call
What it does
strnatcasecmp("Apple", "apple")
Returns 0 because the strings are equal ignoring case.
strnatcasecmp("img2", "IMG10")
Returns a negative number because 2 is less than 10.
usort($files, "strnatcasecmp")
Sorts an array in natural, case-insensitive order.
The function returns a negative number, 0, or a positive number. Since PHP 8.2 the values are always -1, 0, and 1. Compare with < 0, 0, or > 0 to be safe on older versions.
Library declarations
PHP
strnatcasecmp(string $string1, string $string2): int
Parameters
Parameter
Description
string1
Required. The first string to compare.
string2
Required. The second string to compare.
Return Value
Return Value
Description
int
Negative if string1 is less than string2, 0 if they are equal, positive if string1 is greater.
PHP Examples
Example 1 — Sort File Names Naturally
Use strnatcasecmp as a callback to sort names with numbers.
Compare how natural order differs from strcasecmp().
PHP
<?php
echo strnatcasecmp("file10", "file9") > 0
? "natural: file10 comes after file9"
: "natural: file10 comes before file9", PHP_EOL;
echo strcasecmp("file10", "file9") < 0
? "normal: file10 comes before file9"
: "normal: file10 comes after file9", PHP_EOL;
Output
natural: file10 comes after file9
normal: file10 comes before file9
How It Works
Compare file10 and file9 with the natural function.
Natural order reads 10 and 9 as numbers, so 10 is bigger.
strcasecmp compares letter by letter, and "1" is less than "9".
That is why natural comparison is better for names with numbers.
Frequently Asked Questions
It compares two strings in natural order and ignores case. Numbers inside the strings are compared by their numeric value.
Natural order is how humans sort text with numbers: 'img2' comes before 'img10'. Normal string comparison would put 'img10' first because '1' is less than '2'.
strnatcmp() is case-sensitive. strnatcasecmp() ignores case. Both use natural number ordering.
A negative number, 0, or a positive number. From PHP 8.2 these are -1, 0, and 1. Test with < 0, === 0, and > 0.
Use natcasesort($array) to keep keys, or usort($array, 'strnatcasecmp') to reindex the array.