Skip to content
Tutorials Center
My learning

Topics

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
<?php
$files = ["img12", "img10", "img2"];
natsort($files);   // img2, img10, img12 (keys 2, 1, 0)

Try it

PHP Natural order versus string order

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.

PHP Case and a clean list

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

PHP
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 foreach or call array_values() for a fresh list. sort($a, SORT_NATURAL) gives a re-indexed result in one step.
  • Case sensitivity: natsort() puts uppercase before lowercase (like strcmp); natcasesort() ignores case.
  • Digit runs are compared as whole numbers. Dotted version strings such as 1.9 and 1.10 come out in version order, but do not use it for real decimal numbers (use SORT_NUMERIC). For pre-release tags such as 1.0-beta, use version_compare() with usort().
  • 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() or strnatcasecmp() from usort().
  • Descending order: reverse the result with array_reverse(), passing true to preserve keys.
  • Stable since PHP 8.0.