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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

strnatcmp(string $string1, string $string2): int

Parameters

ParameterDescription
string1 The first string.
string2 The second string.

Return value

0 if equal; negative or positive otherwise.

Examples

Natural vs byte orderTry it yourself
<?php
var_dump(strcmp("img10", "img2") < 0);    // byte order
var_dump(strnatcmp("img10", "img2") < 0); // natural order

Output

bool(true)
bool(false)
Sort file namesTry it yourself
<?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

VersionChange
PHP 4.0Added

Was this page helpful?