Sorting arrays is a common task, and PHP offers a variety of functions to help you do just that. The main differences of these functions are:
- Sorting by Keys vs. Values: Some functions sort based on the array keys while others sort by the values
- Maintaining Key-Value Correlation: Depending on the function, the correlation between keys and values might be preserved. In some cases, keys might be reset numerically
- Sort Order: Sorting can be done in various orders, including alphabetical, ascending (low to high), descending (high to low), natural, random, or user-defined.
An important thing to note is that all these sorting functions modify the original array directly. They do not return a new sorted array. So, if you need to keep the original array intact, make sure to create a copy before sorting.
If you want to quickly find the best PHP sorting function for your need, you can use our PHP Sort Function Selector Tool.
Functions to Sort by Value
Function name | Maintains key association | Order of sort |
asort() | yes | ascending |
arsort() | yes | descending |
natcasesort() | yes | natural, case insensitive |
natsort() | yes | natural |
uasort() | yes | user defined |
array_multisort() | string keys yes, int keys no | first array or sort options |
rsort() | no | descending |
shuffle() | no | random |
sort() | no | ascending |
usort() | no | user defined |
Functions to Sort by Key
Function name | Maintains key association | Order of sort |
krsort() | yes | descending |
ksort() | yes | ascending |
uksort() | yes | user defined |
sort Function
The sort function sorts array in place by values in ascending order.
Syntax
sort(array &$array, int $sort_flags = SORT_REGULAR): bool
Parameters
- array: The array to be sorted. Note that this parameter is passed by reference, which means the original array is modified.
- sort_flags (optional): A flag to modify the behavior of the sort. The default is SORT_REGULAR, but there are other options:
- SORT_NUMERIC: Compare items numerically.
- SORT_STRING: Compare items as strings.
- SORT_LOCALE_STRING: Compare items as strings, based on the current locale.
- SORT_NATURAL: Compare items using a “natural order” algorithm (like natsort()).
- SORT_FLAG_CASE: Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort case-insensitively.
Return Value
The function always returns true.
Examples
In this example, the sort() function sorts the $fruits array in ascending order alphabetically.
$fruits = ["banana", "apple", "cherry"];
sort($fruits);
print_r($fruits);
//output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
In the next example, the SORT_NUMERIC flag ensures that the values are compared numerically rather than as strings.
$numbers = ["5", "2", "8", "1"];
sort($numbers, SORT_NUMERIC);
print_r($numbers);
//output:
Array
(
[0] => 1
[1] => 2
[2] => 5
[3] => 8
)
The SORT_NATURAL flag sorts the array in a way that humans would naturally expect, which is especially useful for filenames or any string containing numbers.
$files = ["img12.png", "img10.png", "img2.png", "img1.png"];
sort($files, SORT_NATURAL);
print_r($files);
//output:
Array
(
[0] => img1.png
[1] => img2.png
[2] => img10.png
[3] => img12.png
)
Note that in all cases the sort() function resets the keys of the array. This makes the sort function less suitable for sorting associative arrays:
$languages = [
"es" => "Spanish",
"en" => "English",
"fr" => "French",
"de" => "German"
];
sort( $languages );
print_r( $languages );
//output:
Array
(
[0] => English
[1] => French
[2] => German
[3] => Spanish
)
As you can see in the last example, all keys are reset to numeric keys. If you need to maintain the original keys, you should use asort() instead.
rsort Function
The rsort function works exactly like the sort function with just one difference. It sorts the array in descending order.
asort Function
The asort function sorts an array in place by its values in ascending order while maintaining the association between keys and values. As a result, the asort function is more useful for sorting associative arrays.
Syntax
asort(array &$array, int $sort_flags = SORT_REGULAR): bool
Parameters
- array: The array to be sorted. This parameter is passed by reference, meaning the original array is modified directly.
- sort_flags (optional): A flag to modify the sorting behavior. The default is SORT_REGULAR, but other options include:
- SORT_NUMERIC: Compare items numerically.
- SORT_STRING: Compare items as strings.
- SORT_LOCALE_STRING: Compare items as strings based on the current locale.
- SORT_NATURAL: Compare items using a “natural order” algorithm (similar to natsort()).
- SORT_FLAG_CASE: Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort case-insensitively.
Return Value
The function always returns true.
Examples
In this example, the asort() function sorts the $fruits array by its values in ascending order, while keeping the original keys intact.
$fruits = [
"b" => "banana",
"a" => "apple",
"c" => "cherry"
];
asort($fruits);
print_r($fruits);
//Output
Array
(
[a] => apple
[b] => banana
[c] => cherry
)
With the SORT_NUMERIC flag, the values are compared and sorted numerically.
$numbers = [
"first" => "5",
"second" => "2",
"third" => "8",
"fourth" => "1"
];
asort($numbers, SORT_NUMERIC);
print_r($numbers);
//Output
Array
(
[fourth] => 1
[second] => 2
[first] => 5
[third] => 8
)
Using the SORT_NATURAL flag sorts the values in a way that feels natural to humans, which is especially useful for filenames.
$files = [
"file1" => "img12.png",
"file2" => "img10.png",
"file3" => "img2.png",
"file4" => "img1.png"
];
asort($files, SORT_NATURAL);
print_r($files);
//Output
Array
(
[file4] => img1.png
[file3] => img2.png
[file2] => img10.png
[file1] => img12.png
)
As you can see unlike sort(), asort() maintains the original keys of the array. This is useful when the keys have meaning or when you need to preserve key-value associations.
arsort Function
The arsort function is very similar to the asort function. The only difference is that it sorts the array in descending order. In other words, the arsort function sorts arrays by their values in descending order while maintaining the association between keys and values.
usort Function
The usort function is used to sort an array by values using a user-defined comparison function. This function allows for complex sorting criteria beyond simple alphabetical or numerical order, as you can define exactly how elements should be compared and sorted.
This function does not preserve the keys of the array, meaning that the keys will be reindexed in the sorted array. The comparison function is called repeatedly until the entire array is sorted.
Syntax
usort(array &$array, callable $callback): bool
Parameters
- array: The array to be sorted.
- callback: The comparison function that determines the order of the elements. This function should accept two parameters and return:
- -1 if the first element is considered to be less than the second element,
- 0 if they are considered to be equal,
- 1 if the first element is considered to be greater than the second element.
Return Value
The function always returns true.
Example
$people = [
["name" => "Alice", "age" => 30],
["name" => "Bob", "age" => 25],
["name" => "Charlie", "age" => 35]
];
usort($people, function($a, $b) {
return $a['age'] <=> $b['age'];
});
print_r($people);
//Output
Array
(
[0] => ["name" => "Bob", "age" => 25],
[1] => ["name" => "Alice", "age" => 30],
[2] => ["name" => "Charlie", "age" => 35]
)
In this example, the array of people is sorted by the age key in ascending order.
Note: For large arrays, ensure that the comparison function is optimized, as it will be called multiple times.
uasort Function
The uasort function is used to sort an array by values using a user-defined comparison function, similar to usort, but with a key difference: uasort maintains the association between keys and values in the array. This means that the keys will be preserved in the sorted array.
Similar to usort, this function will call the comparison function repeatedly to determine the order of elements in the array, but unlike usort, it will not reindex the array. The original keys are preserved.
Syntax
uasort(array &$array, callable $callback): bool
Parameters
- array: The array to be sorted.
- callback: The comparison function that determines the order of the elements. This function should accept two parameters and return:
- -1 if the first element is considered to be less than the second element,
- 0 if they are considered to be equal,
- 1 if the first element is considered to be greater than the second element.
Return Value
The function always returns true.
Example
$people = [
"person1" => ["name" => "Alice", "age" => 30],
"person2" => ["name" => "Bob", "age" => 25],
"person3" => ["name" => "Charlie", "age" => 35]
];
uasort($people, function($a, $b) {
return $a['age'] <=> $b['age'];
});
print_r($people);
//Output
Array ( [person2] => Array ( [name] => Bob [age] => 25 ),
[person1] => Array ( [name] => Alice [age] => 30 ),
[person3] => Array ( [name] => Charlie [age] => 35 )
)
In this example, the array of people is sorted by the age key in ascending order, and the original keys are preserved.
natsort Function
The natsort function in PHP is used to sort an array using a natural order algorithm. This is particularly useful for sorting strings that contain numbers in a way that humans would intuitively expect. For instance, it ensures that “file2.txt” comes before “file10.txt” rather than after it, which is how a simple string comparison would sort them.
The natsort function works the same as the asort function with the SORT_NATURAL flag.
Syntax
natsort(array &$array): bool
Parameters
- array: The array to be sorted.
Return Value
The function always returns true.
Example
$files = ["file10.txt", "file2.txt", "file1.txt", "file20.txt"];
natsort($files);
print_r($files);
//Output
Array
(
[2] => file1.txt
[1] => file2.txt
[0] => file10.txt
[3] => file20.txt
)
Notice that the array keys are preserved in the sorting process. If you want to reindex the array, you can use array_values()
As you can see in the next example, the natsort function is case sensitive.
$files = ["File4.txt", "file3.txt", "File2.txt", "file1.txt"];
natsort($files);
print_r($files);
//Output
Array
(
[2] => File2.txt
[0] => File4.txt
[3] => file1.txt
[1] => file3.txt
)
If you want the sort to be case insensitive, you should use the natcasesort() function instead.
natcasesort Function
This function sorts an array in natural order in a case-insensitive manner. It treats uppercase and lowercase letters as equivalent. It works similar to natsort, but unlike natsort it’s case insensitive.
Example
$files = ["File4.txt", "file3.txt", "File2.txt", "file1.txt"];
natcasesort($files);
print_r($files);
//Output
Array
(
[3] => file1.txt
[2] => File2.txt
[1] => file3.txt
[0] => File4.txt
)