strnatcmp
Compares strings in "natural" order — numbers inside strings as numbers.
Syntax
strnatcmp(string $string1, string $string2): intParameters
| Parameter | Type | Description |
|---|---|---|
| $string1 | string | The first string. |
| $string2 | string | The 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.pngNotes
The case-insensitive variant is strnatcasecmp().
See also
In the tutorial
- Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.