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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

natsort(array &$array): true

Parameters

ParameterDescription
array The array to sort (changed in place).

Return value

Always true.

Examples

Natural vs normal sortTry it yourself
<?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
Keys are keptTry it yourself
<?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

VersionChange
PHP 4.0Added
PHP 8.0Sorting is stable: elements that compare equal keep their original order.
PHP 8.2The return type is true (it was bool).

Was this page helpful?