PHP 8 reference · String Functions
PHP strnatcmp() Function
Compare strings in natural order, so "img2" comes before "img10" the way people expect. Case-sensitive.
PHP 8 Since 4.0
Syntax
strnatcmp(string $string1, string $string2): int
Parameters
| Parameter | Description |
|---|---|
string1 |
The first string. |
string2 |
The second string. |
Return value
0 if equal; negative or positive otherwise.
Examples
<?php
var_dump(strcmp("img10", "img2") < 0); // byte order
var_dump(strnatcmp("img10", "img2") < 0); // natural order
Output
bool(true) bool(false)
<?php
$files = ["file10.txt", "file2.txt", "file1.txt"];
usort($files, "strnatcmp");
print_r($files);
Output
Array
(
[0] => file1.txt
[1] => file2.txt
[2] => file10.txt
)Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
Related
strnatcasecmp()· Compare strings in natural order ("a2" before "a10") while ignoring upper and lower case.natsort()· Sort an array in natural order, so "img2" comes before "img10", keeping keys. Case-sensitive.strcmp()· Compare two strings byte by byte, case-sensitively. Returns 0 when equal, less than 0 or more than 0 otherwise.- PHP Strings · tutorial