PHP Reference ยท Array Functions
PHP natsort() and natcasesort() functions
Reference for PHP natsort() and natcasesort(): sort strings in natural, human-friendly order so img2 comes before img10, keeping keys, with case-insensitive form.
natsort() sorts an array in "natural" order, the way a person would. Plain string sorting puts img10 before img2 because the character 1 is smaller than 2. Natural sorting compares runs of digits as whole numbers, so img2 comes first. natcasesort() does the same but ignores letter case.
Both functions work in place, keep the keys and return true. That makes them useful for file names, version-like labels and product codes. If you want the keys replaced by 0, 1, 2, ..., use sort() with SORT_NATURAL instead.
<?php $files = ["img12", "img10", "img2"]; natsort($files); // img2, img10, img12 (keys 2, 1, 0)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
natsort(array &$array): true natcasesort(array &$array): true
| Name | Description |
|---|---|
$array |
The array to sort, passed by reference. Values are compared as strings. |
Return value: always true in PHP 8.2 and later (earlier versions declared bool).
Usage notes
- Keys are preserved. After sorting, loop with
foreachor callarray_values()for a fresh list.sort($a, SORT_NATURAL)gives a re-indexed result in one step. - Case sensitivity:
natsort()puts uppercase before lowercase (likestrcmp);natcasesort()ignores case. - Digit runs are compared as whole numbers. Dotted version strings such as
1.9and1.10come out in version order, but do not use it for real decimal numbers (useSORT_NUMERIC). For pre-release tags such as1.0-beta, useversion_compare()withusort(). - Leading zeros and spaces have special handling; do not rely on the details, test your data.
- No flags and no callback. For natural comparison inside a custom sort, call
strnatcmp()orstrnatcasecmp()fromusort(). - Descending order: reverse the result with
array_reverse(), passingtrueto preserve keys. - Stable since PHP 8.0.