PHP 8 reference · Array Sorting Functions
PHP natsort() Function
Sort an array in natural order, so "img2" comes before "img10", keeping keys. Case-sensitive.
PHP 8 Since 4.0
Syntax
natsort(array &$array): true
Parameters
| Parameter | Description |
|---|---|
array |
The array to sort (changed in place). |
Return value
Always true.
Examples
<?php
$files = ["img12.png", "img10.png", "img2.png", "img1.png"];
sort($files);
echo implode(", ", $files), "\n";
natsort($files);
echo implode(", ", $files), "\n";
Output
img1.png, img10.png, img12.png, img2.png img1.png, img2.png, img10.png, img12.png
<?php
$list = ["v10", "v9", "v1"];
natsort($list);
print_r($list); // keys are kept
print_r(array_values($list)); // renumber if needed
Output
Array
(
[2] => v1
[1] => v9
[0] => v10
)
Array
(
[0] => v1
[1] => v9
[2] => v10
)Version history
Related
natcasesort()· Sort an array in natural order while ignoring case, keeping keys. "Item2" comes before "item10".strnatcmp()· Compare strings in natural order, so "img2" comes before "img10" the way people expect. Case-sensitive.sort()· Sort an array's values in ascending order, in place. Keys are discarded and the result is renumbered from 0.- PHP Arrays · tutorial
- PHP Array Functions · tutorial