The natsort Function
The natsort function sorts an array
as a human would.
This function preserves the associations
between keys and values.
This algorithm is called natural ordering.
The function modifies the array itself.
Syntax
natsort(array &$array, int $flags = SORT_REGULAR): bool
Example
Let's sort an array
using the regular sort function:
<?php
$arr = [
'img12.png',
'img10.png',
'img2.png',
'img1.png',
];
sort($arr);
var_dump($arr);
?>
Code execution result:
[
'img1.png',
'img10.png',
'img12.png',
'img2.png',
]
Example
Now let's perform natural
sorting using the natsort function:
<?php
$arr = [
'img12.png',
'img10.png',
'img2.png',
'img1.png'
];
natsort($arr);
var_dump($arr);
?>
Code execution result:
[
'img1.png',
'img2.png',
'img10.png',
'img12.png',
]
See Also
-
the
sortfunction,
which sorts by element values in ascending order -
the
rsortfunction,
which sorts by element values in descending order -
the
ksortfunction,
which sorts by keys in ascending order -
the
krsortfunction,
which sorts by keys in descending order -
the
asortfunction,
which sorts by element values in ascending order while preserving keys -
the
arsortfunction,
which sorts by element values in descending order while preserving keys -
the
natcasesortfunction,
which sorts naturally in a case-insensitive manner -
the
usortfunction,
which sorts using a callback function -
the
uksortfunction,
which sorts by keys using a callback function -
the
uasortfunction,
which sorts using a callback function while preserving keys -
the
array_multisortfunction,
which sorts multiple arrays