natsort
Sorts strings the way a person would order them.
Syntax
natsort(array &$array): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array being sorted. |
Return value
trueAlways `true`; the array itself is modified.
Examples
Regular and "natural" sorting:
<?php
$files = ['img12.png', 'img10.png', 'img2.png'];
sort($files);
echo implode(', ', $files), "\n";
natsort($files);
echo implode(', ', $files);Output:
img10.png, img12.png, img2.png
img2.png, img10.png, img12.pngNotes
Regular sorting compares character by character, so img10 lands before img2. natsort() keeps the keys.
See also
In the tutorial
- Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.