Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

natsort

Sorts strings the way a person would order them.

Syntax

natsort(array &$array): true

Parameters

ParameterTypeDescription
$arrayarrayThe 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.png

Notes

Regular sorting compares character by character, so img10 lands before img2. natsort() keeps the keys.

See also

  • sort — Sorts an array in ascending order.
  • asort — Sorts an array by value, keeping the keys.
  • usort — Sorts an array by a custom comparison rule.

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.