This question is intended as a reference regarding array sorting issues in PHP. It's easy to think that your particular case is unique and deserves a new question, but most are actually just minor variations on one of the solutions on this page.
If your question was closed as a duplicate of this question, please only ask to reopen your question if you can explain why it is significantly different from all of the following questions.
How to sort an array in PHP?
How to sort acomplexarray in PHP?
How to sort an array of objects in PHP?
Basic one-dimensional array; included. Multidimensional arrays, incl. Array of objects; includes. Sort one array based on another array
Use SPL sorting
Stable sorting
See 1. for a practical answer using PHP's existing functions, for an academically detailed answer about sorting algorithms (that PHP functions implement and that youmightneed in very, very complex situations), See 2.
Okay,decezehas most of the basic methods covered, I will try to look at other types of sorting
Use SPL sorting
SplHeap
Output
SplMaxHeap
The SplMaxHeap class provides the main functionality of the heap, keeping the maximum value at the top.
SplMinHeap
Other types of sorting
Bubble Sort
Excerpted fromWikipedia article about bubble sort:
Basic one-dimensional array
Applicable sorting functions:
Sort
Sort
Classification
Sort
natsort
natcasesort
ksort
krsort
The only difference between them is whether to preserve the key-value association ("
a
" function), whether to sort from low to high or in reverse order ("r
" >" ), whether to sort values or keys ("k
") and how to compare values ("nat
" vs. normal). Seehttp://php.net /manual/en/array.sorting.phpLink to get an overview and more details.Multidimensional arrays, including object arrays
If you want to sort the
$array
by the key "foo" for each entry, you will need acustom comparison function. Thesort
above and related functions work well for simple values that they know how to compare and sort. PHP doesn't simply "know" what to do withcomplex valueslike array('foo' => 'bar', 'baz' => 42); so you need to tell it.To do this, you need to create acomparison function. This function accepts two elements and must return
0
if the elements are considered equal; if the first value is lower, it must return a value lower than0
; if the first value is considered equal A value below0 must return a value above
0
if the first value is higher. This is what is needed:Typically, you need to usean anonymous functionas a callback. If you want to use methods or static methods, seeOther Ways to Specify Callbacks in PHP.
You can then use one of the following functions:
usort
uasort
uksort
Again, they only differ in whether key-value associations are preserved and whether they are sorted by value or key. Please read their documentation for details.
Usage example:
usort
will take two items from the array and call yourcmp
function with them. Socmp()
will callarray('foo' => 'bar', 'baz' => 42)
andin the form
$a$b
as anotherarray('foo' => ..., 'baz' => ...)
. The function then returnsusort
which value is greater or if they are equal.usort
Repeat this process, passing different values for$a
and$b
, until the array is sorted.cmp
The function will be called multiple times,at leastas many values as there are in$array
, anddifferent combinations of values each time code >$a and$b
.To get used to this idea, try the following:
All you do is define a custom way to compare two items and that's all you need. This works for a variety of values.
BTW, this works with any values, which don't have to be complex arrays. You can also compare simple arrays of numbers if you want to do a custom comparison.
sort
Sorting by reference will not return anything useful!Note that arraysare sortedin-place, you do not need to assign the return value to anything.
$array = sort($array)
will replace the array withtrue
, not the sorted array. Justsort($array);
.Custom number comparison
If you want to sort by the numeric keys
baz
, all you need to do is:Thanks tothe power of math, this will return a value 0 depending on whether
$a
is less than, equal to, or greater than$b
.Note that this will not work for
float
values, as they will be simplified toint
and lose precision. Please use explicit-1
,0
, and1
return values instead.Object
If you have an array of objects, it works the same way:
function
You can do anything you need in the comparison function, including calling functions:
String
Shortcut for the first string comparison version:
strcmp
does exactly what is expected fromcmp
, which returns-1
,0
, or1
.Spaceship Operator
PHP 7 introduces thespaceship operator, which unifies and simplifies equal/less than/greater than comparisons across types: p>
Sort by multiple fields
If you want to sort primarily by
foo
, but if two elements'foo
are equal, then sort bybaz
:For those familiar, this is equivalent to a SQL query using
ORDER BY foo, baz
.See alsothis very concise shorthand versionandhow to dynamically create such a comparison function for any number of keys.
Sort by manual static order
If you want to sort the elements into "manual order", e.g."foo", "bar", "baz":
As with all of the above, if you're using PHP 5.3 or higher (and you really should be), use anonymous functions to shorten your code and avoid another global function:
This is a simple way to sort complex multi-dimensional arrays. Again,teach PHP how to determine which of two items is "bigger"; let PHP do the actual sorting.
Additionally, for all of the above, to switch between ascending and descending order, just swap the
$a
and$b
parameters. For example:Sort an array based on another array
There is also a peculiar
array_multisort
, which allows you to sort an array based on: Another:The expected result here is:
Get there using
array_multisort
:Starting with PHP 5.5.0, you can use
array_column
to extract a column from a multidimensional array and sort the array on that column:You can also sort multiple columns in either direction:
Starting with PHP 7.0.0, you can also extract properties from an array of objects.