The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
PHP - Sort Functions For Arrays
In this chapter, we will go through the following PHP array sort functions:
sort[]
- sort arrays in ascending orderrsort[]
- sort arrays in descending orderasort[]
- sort associative arrays in ascending order, according to the valueksort[]
- sort associative arrays in ascending order, according to the keyarsort[]
- sort associative arrays in descending order, according to the valuekrsort[]
- sort associative arrays in descending order, according to the key
Sort Array in Ascending Order - sort[]
The following example sorts the elements of the $cars array in ascending alphabetical order:
Example
Try it Yourself »
The following example sorts the elements of the $numbers array in ascending numerical order:
Sort Array in Descending Order - rsort[]
The following example sorts the elements of the $cars array in descending alphabetical order:
Example
Try it Yourself »
The following example sorts the elements of the $numbers array in descending numerical order:
Sort Array [Ascending Order], According to Value - asort[]
The following example sorts an associative array in ascending order, according to the value:
Example
Try it Yourself »
Sort Array [Ascending Order], According to Key - ksort[]
The following example sorts an associative array in ascending order, according to the key:
Example
Try it Yourself »
Sort Array [Descending Order], According to Value - arsort[]
The following example sorts an associative array in descending order, according to the value:
Example
Try it Yourself »
Sort Array [Descending Order], According to Key - krsort[]
The following example sorts an associative array in descending order, according to the key:
Example
Try it Yourself »
Complete PHP Array Reference
For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!
PHP Exercises
[PHP 4, PHP 5, PHP 7, PHP 8]
sort — Sort an array in ascending order
Description
sort[array &$array
, int $flags
= SORT_REGULAR
]: bool
Note:
If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
Note: This function assigns new keys to the elements in
array
. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
Note:
Resets array's internal pointer to the first element.
Parameters
array
The input array.
flags
The optional second parameter flags
may be used to modify the sorting behavior using these values:
Sorting type flags:
-
SORT_REGULAR
- compare items normally; the details are described in the comparison operators section -
SORT_NUMERIC
- compare items numerically -
SORT_STRING
- compare items as strings -
SORT_LOCALE_STRING
- compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale[] -
SORT_NATURAL
- compare items as strings using "natural ordering" like natsort[] -
SORT_FLAG_CASE
- can be combined [bitwise OR] withSORT_STRING
orSORT_NATURAL
to sort strings case-insensitively
Return Values
Always returns true
.
Examples
Example #1 sort[] example
The above example will output:
fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange
The fruits have been sorted in alphabetical order.
Example #2 sort[] example using case-insensitive natural ordering
The above example will output:
fruits[0] = Orange1 fruits[1] = orange2 fruits[2] = Orange3 fruits[3] = orange20
The fruits have been sorted like natcasesort[].
Notes
Note: Like most PHP sorting functions, sort[] uses an implementation of » Quicksort. The pivot is chosen in the middle of the partition resulting in an optimal time for already sorted arrays. This is however an implementation detail you shouldn't rely on.
Warning
Be careful when sorting arrays with mixed types values because sort[] can produce unexpected results, if flags
is SORT_REGULAR
.
See Also
- rsort[] - Sort an array in descending order
- The comparison of array sorting functions
phpdotnet at m4tt dot co dot uk ¶
12 years ago
Simple function to sort an array by a specific key. Maintains index association.
aminkhoshzahmat at gmail dot com ¶
2 years ago
Let's say we have a list of names, and it is not sorted.
If you want to sort alphabeticaly no matter it is upper or lower case:
Result is :
Array
[
[0] => Amin
[1] => Armin
[2] => Somayeh // actually it's not sort alphabetically from here!
[3] => amir // comparison is based on ASCII values.
[4] => armita
[5] => sarah
]
Result is:
Array
[
[0] => Amin
[1] => amir
[2] => Armin
[3] => armita
[4] => sarah
[5] => Somayeh
]
ajanata at gmail dot com ¶
10 years ago
This took me longer than it should have to figure out, but if you want the behavior of sort[$array, SORT_STRING] [that is, re-indexing the array unlike natcasesort] in a case-insensitive manner, it is a simple matter of doing usort[$array, strcasecmp].
joris at mangrove dot nl ¶
15 years ago
Commenting on note //www.php.net/manual/en/function.sort.php#62311 :
Sorting an array of objects will not always yield the results you desire.
As pointed out correctly in the note above, sort[] sorts the array by value of the first member variable. However, you can not always assume the order of your member variables! You must take into account your class hierarchy!
By default, PHP places the inherited member variables on top, meaning your first member variable is NOT the first variable in your class definition!
However, if you use code analyzers or a compile cache, things can be very different. E.g., in eAccelerator, the inherited member variables are at the end, meaning you get different sort results with caching on or off.
Conclusion:
Never use sort on arrays with values of a type other than scalar or array.
Walter Tross ¶
10 years ago
unless you specify the second argument, "regular" comparisons will be used. I quote from the page on comparison operators:
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically."
What this means is that "10" < "1a", and "1a" < "2", but "10" > "2". In other words, regular PHP string comparisons are not transitive.
This implies that the output of sort[] can in rare cases depend on the order of the input array:
danm68 at gmail dot com ¶
13 years ago
sort[] used with strings doesn't sort just alphabetically. It sorts all upper-case strings alphabetically first and then sorts lower-case strings alphabetically second.
Just in case anyone was as confused as I was and I've never seen this mentioned anywhere.
peek at mailandnews dot com ¶
21 years ago
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:
usort[$listing, 'strcasecmp'];
This didn't work [why not?], but you can do a proper case insensitive sort like this:
usort[$listing, create_function['$a,$b','return strcasecmp[$a,$b];']];
eriewave at hotmail dot com ¶
12 years ago
If you need to sort an array containing some equivalent values and you want the equivalents to end up next to each other in the overall order [similar to a MySQL's ORDER BY output], rather than breaking the function, do this:
-Dirk
-When the sort[] function finds two equivalents, it will sort them arbitrarily by their key #'s as a second parameter.
williamprogphp at[pleaseNOTSPAM] yahoo d ¶
8 years ago
In order to make some multidimensional quick sort implementation, take advantage of this stuff
I make it using the idea from pageconfig dot com
tks for viewing
alishahnovin at hotmail dot com ¶
15 years ago
I had a multidimensional array, which needed to be sorted by one of the keys. This is what I came up with...
Ex:
g8z at yahoo dot com ¶
16 years ago