Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

strnatcmp

Compares strings in "natural" order — numbers inside strings as numbers.

Syntax

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

Parameters

ParameterTypeDescription
$string1stringThe first string.
$string2stringThe second string.

Return value

intA negative number, `0` or a positive number.

Examples

Regular and natural comparison:

<?php
 
$files = ['img12.png', 'img10.png', 'img2.png'];
 
sort($files);
echo implode(', ', $files), "\n";
 
usort($files, 'strnatcmp');
echo implode(', ', $files);

Output:

img10.png, img12.png, img2.png
img2.png, img10.png, img12.png

Notes

The case-insensitive variant is strnatcasecmp().

See also

  • natsort — Sorts strings the way a person would order them.
  • strcmp — Compares two strings.
  • usort — Sorts an array by a custom comparison rule.

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.