PHP natsort: How to Sort Arrays Using Natural Order
This article explains how to use the natsort() function
in PHP to sort arrays using a natural order algorithm. You will learn
the difference between standard alphanumeric sorting and natural
sorting, see practical code examples demonstrating the function in
action, and learn how to handle case-sensitivity during the sorting
process.
What is Natural Order Sorting?
In standard computer sorting algorithms (like PHP’s default
sort()), strings are compared character-by-character. This
often leads to unnatural results when dealing with strings containing
numbers. For example, a standard sort will place
"img12.png" before "img2.png" because the
character "1" comes before "2".
Natural order sorting orders strings the way a human naturally would.
Using a natural order algorithm, "img2.png" is correctly
sorted before "img12.png".
Using the natsort()
Function
PHP provides the built-in natsort() function to achieve
this. It sorts the elements of an array using natural order and
maintains the original key-value associations.
Here is a basic example comparing sort() and
natsort():
$files1 = ["img12.png", "img10.png", "img2.png", "img1.png"];
$files2 = $files1;
// Standard sorting
sort($files1);
echo "Standard sort:\n";
print_r($files1);
// Natural order sorting
natsort($files2);
echo "\nNatural order sort:\n";
print_r($files2);Output:
Standard sort:
Array
(
[0] => img1.png
[1] => img10.png
[2] => img12.png
[3] => img2.png
)
Natural order sort:
Array
(
[3] => img1.png
[2] => img2.png
[1] => img10.png
[0] => img12.png
)
As shown in the output, natsort() correctly identifies
that 2 is smaller than 10 and 12,
and it preserves the original array keys (e.g., "img1.png"
retains its original index of 3).
Case-Insensitive Natural Sorting
The natsort() function is case-sensitive, meaning
uppercase letters will be sorted before lowercase letters. If you want
to sort strings naturally without regard to case, you should use the
natcasesort() function instead.
Here is an example demonstrating the difference:
$images = ["IMG2.png", "img10.png", "img1.png", "IMG12.png"];
// Case-sensitive natural sort
natsort($images);
echo "Case-sensitive (natsort):\n";
print_r($images);
// Case-insensitive natural sort
natcasesort($images);
echo "\nCase-insensitive (natcasesort):\n";
print_r($images);Output:
Case-sensitive (natsort):
Array
(
[0] => IMG2.png
[3] => IMG12.png
[2] => img1.png
[1] => img10.png
)
Case-insensitive (natcasesort):
Array
(
[2] => img1.png
[0] => IMG2.png
[1] => img10.png
[3] => IMG12.png
)
Key Behavior to Remember
- Key Preservation: Both
natsort()andnatcasesort()maintain the key-value associations of the array. If you need to reset the keys to consecutive integers after sorting, use thearray_values()function on the sorted array. - In-place Sorting: These functions modify the
original array directly and return
trueon success orfalseon failure, rather than returning a new sorted array.