PHP strnatcmp() Function

Definition
In PHP, strnatcmp() compares two strings using natural order, and it is case-sensitive.
Numbers inside the text are compared by value, so "img2" is less than "img10", unlike a plain string comparison.
Syntax
Call strnatcmp() with the values you need. Start with this line.
$result = strnatcmp("img12.png", "img10.png");
| Call | What it does |
|---|
strnatcmp("img12.png", "img10.png") | Returns a positive number because 12 is greater than 10. |
strnatcmp("Apple", "apple") | Returns a negative number because uppercase comes first. |
usort($items, "strnatcmp") | Sorts an array in natural order. |
For case-insensitive natural comparison, use strnatcasecmp(). Since PHP 8.2 the result is always -1, 0, or 1.
Library declarations
strnatcmp(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 — Compare Numbered Names
Natural order treats the numbers as numbers.
<?php
$result = strnatcmp("img12.png", "img10.png");
if ($result > 0) {
echo "img12.png comes after img10.png", PHP_EOL;
}
img12.png comes after img10.png
How It Works
- Compare two file names that differ in a number.
- The text before the number is the same.
- PHP compares 12 and 10 as numbers, and 12 is bigger.
- The result is positive, so the first name comes later.
Example 2 — Case Matters
Unlike strnatcasecmp(), this function treats upper and lower case as different.
<?php
$result = strnatcmp("Apple", "apple");
echo $result < 0
? "Apple comes before apple"
: "Apple does not come before apple", PHP_EOL;
How It Works
- Compare "Apple" with "apple".
- Uppercase "A" has a lower byte value than lowercase "a".
- The result is negative.
- Use strnatcasecmp() if you want these to be equal.
Frequently Asked Questions
It compares two strings using natural order. Numbers are compared by value, and letters are compared in a case-sensitive way.
strcmp() compares character by character, so 'img10' comes before 'img2'. strnatcmp() understands numbers and puts 'img2' first.
Yes. Uppercase letters sort before lowercase ones. Use strnatcasecmp() to ignore case.
A negative number, 0, or a positive number. From PHP 8.2 it is always -1, 0, or 1.
Use usort($array, 'strnatcmp'). You can also call natsort($array), which does natural sorting and keeps the keys.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful