This question is intended as a reference for questions about sorting arrays in PHP. It is easy to think that your particular case is unique, and worthy of a new question, but most are actually minor variations of one of the solutions on this page.

If your question is closed as a duplicate of this one, please ask for your question to be reopened only if you can explain why it differs markedly from all of the below.

How do I sort an array in PHP?
How do I sort a complex array in PHP?
How do I sort an array of objects in PHP?

For the practical answer using PHP's existing functions see 1., for the academic in-detail answer on sorting algorithms (which PHP's functions implement and which you may need for really, really complex cases), see 2.

Problem: 99% of the unique snowflake questions (ha) are one-offs with absolutely no pre-question research :|
– jterryJun 28 '13 at 11:58

@jterry Exactly, that's why I made this to finally have a good reference question to close against. Answering each unique snowflake individually doesn't help anyone. :)
– deceze♦Jun 28 '13 at 11:59

3

I think people should simply take a look at php.net
– Alexander JardimJun 28 '13 at 12:03

2

We have those answers already, I suggest you list-link the best answers inside each answer here instead of duplicating (or re-writing) the content. Also arrays tend to be seen individually so the work remains to close-vote against the dupes in any case.
– hakreJun 28 '13 at 12:04

9 Answers
9

Basic one dimensional arrays

$array = array(3, 5, 2, 8);

Applicable sort functions:

sort

rsort

asort

arsort

natsort

natcasesort

ksort

krsort

The difference between those is merely whether key-value associations are kept (the "a" functions), whether it sorts low-to-high or reverse ("r"), whether it sorts values or keys ("k") and how it compares values ("nat" vs. normal). See http://php.net/manual/en/array.sorting.php for an overview and links to further details.

Multi dimensional arrays, including arrays of objects

If you want to sort $array by the key 'foo' of each entry, you need a custom comparison function. The above sort and related functions work on simple values that they know how to compare and sort. PHP does not simply "know" what to do with a complex value like array('foo' => 'bar', 'baz' => 42) though; so you need to tell it.

To do that, you need to create a comparison function. That function takes two elements and must return 0 if these elements are considered equal, a value lower than 0 if the first value is lower and a value higher than 0 if the first value is higher. That's all that's needed:

Again, they only differ in whether they keep key-value associations and sort by values or keys. Read their documentation for details.

Example usage:

usort($array, 'cmp');

usort will take two items from the array and call your cmp function with them. So cmp() will be called with $a as array('foo' => 'bar', 'baz' => 42) and $b as another array('foo' => ..., 'baz' => ...). The function then returns to usort which of the values was larger or whether they were equal. usort repeats this process passing different values for $a and $b until the array is sorted. The cmp function will be called many times, at least as many times as there are values in $array, with different combinations of values for $a and $b every time.

@Rizier123 I certainly applaud the effort, it's a very good writeup; but I would prefer it if you posted it as separate answer, even if it's very similar. Your rewrite contains a lot of details (pass by reference, big table etc.), but that detail distracts from the smooth introduction to the core topic of the workings of the comparison function, IMHO. I explicitly refer to the manual several times on purpose, because that's where such detail should be looked up; no need to repeat it here and distract from the core idea I'm trying to convey.
– deceze♦Jun 3 '16 at 1:49

Other Types of Sort

Bubble Sort

Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

Selection sort

In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

Insertion sort

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:

Shellsort

Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. It generalizes an exchanging sort, such as insertion or bubble sort, by starting the comparison and exchange of elements with elements that are far apart before finishing with neighboring elements.

Comb sort

Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.

Merge sort

In computer science, a merge sort (also commonly spelled mergesort) is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output

Quicksort

Quicksort, or partition-exchange sort, is a sorting algorithm developed by Tony Hoare that, on average, makes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare.

Radix sort

In computer science, radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.

@deceze you covered all the basics .. i had to look for another way to be relevant :)
– BabaJun 28 '13 at 12:18

5

I don't see anything wrong with the more academic sorting methods :) alot less useful for most applications but occasionally they may be asked for / required is handy to have a reference especially since I'd forgotton about most of these over time
– DaveJun 28 '13 at 12:18

Actually, for quick sort it is recommended to select pivot as a median of three values: first, middle and last elements. This is my example for pivot seletion. That allows to avoid worst-case reverse-sorted array (which causes O(n^2) comparisons if we'll use just first element as pivot)
– Alma DoMay 3 '14 at 21:10

I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuqJan 13 '16 at 10:18

I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike NguyenMar 10 '16 at 4:03

The keen observer may have noticed that the array sorting algorithm (QuickSort) didn't produce a stable outcome and that the original order between words of the same first letter wasn't preserved. This case is trivial and we should have compared the whole string, but let's assume your use-case is more complicated, such as two consecutive sorts on different fields that shouldn't cancel out each other's work.

The Schwartzian transform

The Schwartzian transform, also referred to as the decorate-sort-undecorate idiom, effects a stable sort with an inherently unstable sorting algorithm.

First, you decorate each array element with another array comprising a primary key (the value) and a secondary key (its index or position):

Your phrase "effects a stable sort with an inherently unstable sorting algorithm" was the ah-ha moment for me. The wikipedia page has no mention of the word stable, which seems to me to be the beauty of the transform. Shame.
– Tyler CollierMar 2 '15 at 5:44

1

@TylerCollier Yeah, you need to read between the lines of that Wikipedia reference ... I saved you the trouble of doing that ;-)
– Ja͢ckMar 2 '15 at 5:49

Just remember that this will remove any previous relative order (for instance, the first "July" object in the pre-sorted list may end up at the end of the group of July objects after sorting). See "Stable Sort" above.
– George LangleyJul 8 '14 at 18:33

LINQ

In .NET, LINQ is frequently used for sorting, which provides a much nicer syntax over comparison functions, especially when objects need to be sorted by multiple fields. There're several ports of LINQ to PHP, including YaLinqo library*. With it, arrays can be sorted with a single line without writing complex comparison functions.

Here, '$v->count' is a shorthand for function ($v) { return $v->count; } (either can be used). These method chains return iterators, iterators can be transformed to arrays by adding ->toArray() in the end if needed.

LINQ contains many more methods inspired by SQL: filtering, grouping, joining, aggregating etc. It's best suited for cases when complex transformations on arrays and objects need to be performed without relying on databases.

* developed by me, see readme for more details and comparison with other LINQ ports

// Lets assume we have class User(name, age) with properties name and age
// and public methods getName() and getAge()
$users = [
new User('Robert', 20),
new User('Alex', 30),
new User('Jack', 25),
];
// Sort list of objects by property value (sort list of users by their name)
$sortedByName = sorted($users, propertyGetter('name'));
$sortedByNameDesc = sorted($users, true, propertyGetter('name'));
// propertyGetter('name') returns a function which takes an object
// and returns the value of its 'name' property
// Sort list of objects by method result (sort list of users by their age)
$sortedByAge = sorted($users, methodCaller('getAge'));
$sortedByAgeDesc = sorted($users, true, methodCaller('getAge'));
// methodCaller('getAge') returns a function which takes an object
// and returns the result of its getAge() method

Now array is sorted in descending order.Ok, Let's consider an associative array.I will give an associative array(Associative array means that, An array whose each index has unique key value.) like this,

1) The example and code are inconsistent. 2) This is already explained in excruciating detail in above answers. 3) Are you possibly trying to respond to a different question?
– deceze♦May 25 '16 at 7:49

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).