How can I sort arrays and data in PHP?
up vote
260
down vote
favorite
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?
Basic one dimensional arrays; Incl. Multi dimensional arrays, incl. arrays of objects; Incl. Sorting one array based on another
Sorting with SPL
Stable sort
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.
php arrays sorting object spl
|
show 6 more comments
up vote
260
down vote
favorite
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?
Basic one dimensional arrays; Incl. Multi dimensional arrays, incl. arrays of objects; Incl. Sorting one array based on another
Sorting with SPL
Stable sort
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.
php arrays sorting object spl
1
Problem: 99% of the unique snowflake questions (ha) are one-offs with absolutely no pre-question research :|
– jterry
Jun 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 Jardim
Jun 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.
– hakre
Jun 28 '13 at 12:04
1
@deceze: If nobody RTFM, nobody will also RTFQA - the existing Q&A :)
– hakre
Jun 28 '13 at 12:09
|
show 6 more comments
up vote
260
down vote
favorite
up vote
260
down vote
favorite
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?
Basic one dimensional arrays; Incl. Multi dimensional arrays, incl. arrays of objects; Incl. Sorting one array based on another
Sorting with SPL
Stable sort
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.
php arrays sorting object spl
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?
Basic one dimensional arrays; Incl. Multi dimensional arrays, incl. arrays of objects; Incl. Sorting one array based on another
Sorting with SPL
Stable sort
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.
php arrays sorting object spl
php arrays sorting object spl
edited Jun 4 at 11:50
IMSoP
45.4k65693
45.4k65693
asked Jun 28 '13 at 11:53
deceze♦
390k61529685
390k61529685
1
Problem: 99% of the unique snowflake questions (ha) are one-offs with absolutely no pre-question research :|
– jterry
Jun 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 Jardim
Jun 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.
– hakre
Jun 28 '13 at 12:04
1
@deceze: If nobody RTFM, nobody will also RTFQA - the existing Q&A :)
– hakre
Jun 28 '13 at 12:09
|
show 6 more comments
1
Problem: 99% of the unique snowflake questions (ha) are one-offs with absolutely no pre-question research :|
– jterry
Jun 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 Jardim
Jun 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.
– hakre
Jun 28 '13 at 12:04
1
@deceze: If nobody RTFM, nobody will also RTFQA - the existing Q&A :)
– hakre
Jun 28 '13 at 12:09
1
1
Problem: 99% of the unique snowflake questions (ha) are one-offs with absolutely no pre-question research :|
– jterry
Jun 28 '13 at 11:58
Problem: 99% of the unique snowflake questions (ha) are one-offs with absolutely no pre-question research :|
– jterry
Jun 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
@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
3
I think people should simply take a look at php.net
– Alexander Jardim
Jun 28 '13 at 12:03
I think people should simply take a look at php.net
– Alexander Jardim
Jun 28 '13 at 12:03
2
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.
– hakre
Jun 28 '13 at 12:04
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.
– hakre
Jun 28 '13 at 12:04
1
1
@deceze: If nobody RTFM, nobody will also RTFQA - the existing Q&A :)
– hakre
Jun 28 '13 at 12:09
@deceze: If nobody RTFM, nobody will also RTFQA - the existing Q&A :)
– hakre
Jun 28 '13 at 12:09
|
show 6 more comments
9 Answers
9
active
oldest
votes
up vote
139
down vote
accepted
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
$array = array(
array('foo' => 'bar', 'baz' => 42),
array('foo' => ..., 'baz' => ...),
...
);
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:
function cmp(array $a, array $b) {
if ($a['foo'] < $b['foo']) {
return -1;
} else if ($a['foo'] > $b['foo']) {
return 1;
} else {
return 0;
}
}
Often, you will want to use an anonymous function as the callback. If you want to use a method or static method, see the other ways of specifying a callback in PHP.
You then use one of these functions:
usort
uasort
uksort
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.
To get used to this idea, try this:
function cmp($a, $b) {
echo 'cmp called with $a:', PHP_EOL;
var_dump($a);
echo 'and $b:', PHP_EOL;
var_dump($b);
}
All you did was define a custom way to compare two items, that's all you need. That works with all sorts of values.
By the way, this works on any value, the values don't have to be complex arrays. If you have a custom comparison you want to do, you can do it on a simple array of numbers too.
sort
sorts by reference and does not return anything useful!
Note that the array sorts in place, you do not need to assign the return value to anything. $array = sort($array)
will replace the array with true
, not with a sorted array. Just sort($array);
works.
Custom numeric comparisons
If you want to sort by the baz
key, which is numeric, all you need to do is:
function cmp(array $a, array $b) {
return $a['baz'] - $b['baz'];
}
Thanks to The PoWEr oF MATH this returns a value < 0, 0 or > 0 depending on whether $a
is lower than, equal to or larger than $b
.
Note that this won't work well for float
values, since they'll be reduced to an int
and lose precision. Use explicit -1
, 0
and 1
return values instead.
Objects
If you have an array of objects, it works the same way:
function cmp($a, $b) {
return $a->baz - $b->baz;
}
Functions
You can do anything you need inside a comparison function, including calling functions:
function cmp(array $a, array $b) {
return someFunction($a['baz']) - someFunction($b['baz']);
}
Strings
A shortcut for the first string comparison version:
function cmp(array $a, array $b) {
return strcmp($a['foo'], $b['foo']);
}
strcmp
does exactly what's expected of cmp
here, it returns -1
, 0
or 1
.
Spaceship operator
PHP 7 introduced the spaceship operator, which unifies and simplifies equal/smaller/larger than comparisons across types:
function cmp(array $a, array $b) {
return $a['foo'] <=> $b['foo'];
}
Sorting by multiple fields
If you want to sort primarily by foo
, but if foo
is equal for two elements sort by baz
:
function cmp(array $a, array $b) {
if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
return $cmp;
} else {
return $a['baz'] - $b['baz'];
}
}
For those familiar, this is equivalent to an SQL query with ORDER BY foo, baz
.
Also see this very neat shorthand version and how to create such a comparison function dynamically for an arbitrary number of keys.
Sorting into a manual, static order
If you want to sort elements into a "manual order" like "foo", "bar", "baz":
function cmp(array $a, array $b) {
static $order = array('foo', 'bar', 'baz');
return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}
For all the above, if you're using PHP 5.3 or higher (and you really should), use anonymous functions for shorter code and to avoid having another global function floating around:
usort($array, function (array $a, array $b) { return $a['baz'] - $b['baz']; });
That's how simple sorting a complex multi-dimensional array can be. Again, just think in terms of teaching PHP how to tell which of two items is "greater"; let PHP do the actual sorting.
Also for all of the above, to switch between ascending and descending order simply swap the $a
and $b
arguments around. E.g.:
return $a['baz'] - $b['baz']; // ascending
return $b['baz'] - $a['baz']; // descending
Sorting one array based on another
And then there's the peculiar array_multisort
, which lets you sort one array based on another:
$array1 = array( 4, 6, 1);
$array2 = array('a', 'b', 'c');
The expected result here would be:
$array2 = array('c', 'a', 'b'); // the sorted order of $array1
Use array_multisort
to get there:
array_multisort($array1, $array2);
As of PHP 5.5.0 you can use array_column
to extract a column from a multi dimensional array and sort the array on that column:
array_multisort(array_column($array, 'foo'), SORT_DESC, $array);
As of PHP 7.0.0 you can also extract properties from an array of objects.
If you have more common cases, feel free to edit this answer.
The numeric comparison function doesn't work for float values; I'm sure you know what I mean :)
– Ja͢ck
Jun 28 '13 at 12:07
True, added a note.
– deceze♦
Jun 28 '13 at 12:09
1
For the static order, I would applyarray_flip()
to make use of speedier position lookup, e.g.$order[$a['foo']]
instead ofarray_search($a['foo'], $order)
.
– Ja͢ck
Jun 28 '13 at 23:58
Might be a bit of a big edit: gist.github.com/Rizier123/24a6248758b53245a63e839d8e08a32b but if you think it is an improvement and I included everything essential I can apply it.
– Rizier123
Jun 2 '16 at 16:30
@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
|
show 1 more comment
up vote
135
down vote
Well most basic methods are already covered by deceze I would try to look at other types of sort
Sorting with SPL
SplHeap
class SimpleHeapSort extends SplHeap {
public function compare($a, $b) {
return strcmp($a, $b);
}
}
// Let's populate our heap here (data of 2009)
$heap = new SimpleHeapSort();
$heap->insert("a");
$heap->insert("b");
$heap->insert("c");
echo implode(PHP_EOL, iterator_to_array($heap));
Output
c
b
a
SplMaxHeap
The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.
$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(2);
$heap->insert(3);
SplMinHeap
The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.
$heap = new SplMinHeap ();
$heap->insert(3);
$heap->insert(1);
$heap->insert(2);
Other Types of Sort
Bubble Sort
From the Wikipedia article on 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.
function bubbleSort(array $array) {
$array_size = count($array);
for($i = 0; $i < $array_size; $i ++) {
for($j = 0; $j < $array_size; $j ++) {
if ($array[$i] < $array[$j]) {
$tem = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tem;
}
}
}
return $array;
}
Selection sort
From the Wikipedia article on 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.
function selectionSort(array $array) {
$length = count($array);
for($i = 0; $i < $length; $i ++) {
$min = $i;
for($j = $i + 1; $j < $length; $j ++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$tmp = $array[$min];
$array[$min] = $array[$i];
$array[$i] = $tmp;
}
return $array;
}
Insertion sort
From the Wikipedia article on 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:
function insertionSort(array $array) {
$count = count($array);
for($i = 1; $i < $count; $i ++) {
$j = $i - 1;
// second element of the array
$element = $array[$i];
while ( $j >= 0 && $array[$j] > $element ) {
$array[$j + 1] = $array[$j];
$array[$j] = $element;
$j = $j - 1;
}
}
return $array;
}
Shellsort
From the Wikipedia article on 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.
function shellSort(array $array) {
$gaps = array(
1,
2,
3,
4,
6
);
$gap = array_pop($gaps);
$length = count($array);
while ( $gap > 0 ) {
for($i = $gap; $i < $length; $i ++) {
$tmp = $array[$i];
$j = $i;
while ( $j >= $gap && $array[$j - $gap] > $tmp ) {
$array[$j] = $array[$j - $gap];
$j -= $gap;
}
$array[$j] = $tmp;
}
$gap = array_pop($gaps);
}
return $array;
}
Comb sort
From the Wikipedia article on 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.
function combSort(array $array) {
$gap = count($array);
$swap = true;
while ( $gap > 1 || $swap ) {
if ($gap > 1)
$gap /= 1.25;
$swap = false;
$i = 0;
while ( $i + $gap < count($array) ) {
if ($array[$i] > $array[$i + $gap]) {
// swapping the elements.
list($array[$i], $array[$i + $gap]) = array(
$array[$i + $gap],
$array[$i]
);
$swap = true;
}
$i ++;
}
}
return $array;
}
Merge sort
From the Wikipedia article on 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
function mergeSort(array $array) {
if (count($array) <= 1)
return $array;
$left = mergeSort(array_splice($array, floor(count($array) / 2)));
$right = mergeSort($array);
$result = array();
while ( count($left) > 0 && count($right) > 0 ) {
if ($left[0] <= $right[0]) {
array_push($result, array_shift($left));
} else {
array_push($result, array_shift($right));
}
}
while ( count($left) > 0 )
array_push($result, array_shift($left));
while ( count($right) > 0 )
array_push($result, array_shift($right));
return $result;
}
Quicksort
From the Wikipedia article on 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.
function quickSort(array $array) {
if (count($array) == 0) {
return $array;
}
$pivot = $array[0];
$left = $right = array();
for($i = 1; $i < count($array); $i ++) {
if ($array[$i] < $pivot) {
$left = $array[$i];
} else {
$right = $array[$i];
}
}
return array_merge(quickSort($left), array(
$pivot
), quickSort($right));
}
Permutation sort
From the Wikipedia article on Permutation sort:
Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one.
function permutationSort($items, $perms = array()) {
if (empty($items)) {
if (inOrder($perms)) {
return $perms;
}
} else {
for($i = count($items) - 1; $i >= 0; -- $i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permutationSort($newitems, $newperms);
if ($res) {
return $res;
}
}
}
}
function inOrder($array) {
for($i = 0; $i < count($array); $i ++) {
if (isset($array[$i + 1])) {
if ($array[$i] > $array[$i + 1]) {
return False;
}
}
}
return True;
}
Radix sort
From the Wikipedia article on 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.
// Radix Sort for 0 to 256
function radixSort($array) {
$n = count($array);
$partition = array();
for($slot = 0; $slot < 256; ++ $slot) {
$partition = array();
}
for($i = 0; $i < $n; ++ $i) {
$partition[$array[$i]->age & 0xFF] = &$array[$i];
}
$i = 0;
for($slot = 0; $slot < 256; ++ $slot) {
for($j = 0, $n = count($partition[$slot]); $j < $n; ++ $j) {
$array[$i ++] = &$partition[$slot][$j];
}
}
return $array;
}
4
@deceze you covered all the basics .. i had to look for another way to be relevant :)
– Baba
Jun 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
– Dave
Jun 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 causesO(n^2)
comparisons if we'll use just first element as pivot)
– Alma Do
May 3 '14 at 21:10
I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuq
Jan 13 '16 at 10:18
I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike Nguyen
Mar 10 '16 at 4:03
add a comment |
up vote
43
down vote
Stable sort
Let's say you have an array like this:
['Kale', 'Kaleidoscope', 'Aardvark', 'Apple', 'Leicester', 'Lovely']
And now you want to sort on the first letter only:
usort($array, function($a, $b) {
return strcmp($a[0], $b[0]);
});
The outcome is this:
['Apple', 'Aardvark', 'Kale', 'Kaleidoscope', 'Lovely', 'Leicester']
The sort wasn't stable!
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):
array_walk($array, function(&$element, $index) {
$element = array($element, $index); // decorate
});
This transforms the array into this:
[
['Kale', 0], ['Kaleidoscope', 1],
['Aardvark', 2], ['Apple', 3],
['Leicester', 4], ['Lovely', 5]
]
Now, we adjust the comparison step; we compare the first letter again, but if they're the same, the secondary key is used to retain the original ordering:
usort($array, function($a, $b) {
// $a[0] and $b[0] contain the primary sort key
// $a[1] and $b[1] contain the secondary sort key
$tmp = strcmp($a[0][0], $b[0][0]);
if ($tmp != 0) {
return $tmp; // use primary key comparison results
}
return $a[1] - $b[1]; // use secondary key
});
Afterwards, we undecorate:
array_walk($array, function(&$element) {
$element = $element[0];
});
The final result:
['Aardvark', 'Apple', 'Kale', 'Kaleidoscope', 'Leicester', 'Lovely']
What about reuse?
You had to rewrite your comparison function to work with the transformed array elements; you may not want to edit your delicate comparison functions, so here's a wrapper for the comparison function:
function stablecmp($fn)
{
return function($a, $b) use ($fn) {
if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
return $tmp;
} else {
return $a[1] - $b[1];
}
};
}
Let's write the sort step using this function:
usort($array, stablecmp(function($a, $b) {
return strcmp($a[0], $b[0]);
}));
Voila! Your pristine comparison code is back.
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 Collier
Mar 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͢ck
Mar 2 '15 at 5:49
add a comment |
up vote
15
down vote
As of PHP 5.3 with closures it is also possible to use a closure to determine the order of your sort.
For example assuming $array is an array of objects that contain a month property.
$orderArray = array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");
usort($array, function($a, $b) use ($orderArray){
return array_search($a->month, $orderArray) - array_search($b->month, $orderArray);
});
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 Langley
Jul 8 '14 at 18:33
add a comment |
up vote
9
down vote
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.
$sortedByName = from($objects)->orderBy('$v->name');
$sortedByCount = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
Comparisons can be further customized by passing a callback as a second argument, for example:
$sortedByFilenameNat = from($objects)->orderBy('$v->filename', 'strnatcmp');
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.
Internally, orderBy
and related methods call appropriate array sorting functions (uasort
, krsort
, multisort
, usort
etc.).
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
add a comment |
up vote
3
down vote
Multidimensional sort by key value
Natural sort of a multidimensional array by a key value and also keep the original order(do not shuffle the main keys):
function multisortByKeyValue( $k, $arr ) {
$ids = array();
$index = 1;
foreach ( $arr as $key => $row ) {
$ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
$index ++;
}
natsort( $ids );
$arr = array_merge( $ids, $arr );
return $arr;
}
Test case:
$arr = array(
'id1' => array(
'label' => 'ID 1',
'priority' => 30,
),
'id2' => array(
'label' => 'ID 2',
'priority' => 70,
),
'id3' => array(
'label' => 'ID 3',
'priority' => 20,
),
'id4' => array(
'label' => 'ID 4',
'priority' => 30,
),
);
$sorted = multisortByKeyValue( 'priority', $arr );
// $sorted equals to:
/*
array (
'id3' => array (
'label' => 'ID 3',
'priority' => 20,
),
'id1' => array (
'label' => 'ID 1',
'priority' => 30,
),
'id4' => array (
'label' => 'ID 4',
'priority' => 30,
),
'id2' => array (
'label' => 'ID 2',
'priority' => 70,
),
)
*/
add a comment |
up vote
2
down vote
It is very convenient to sort arrays with sorted function from Nspl:
Basic sorting
// Sort array
$sorted = sorted([3, 1, 2]);
// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);
Sorting by function result
// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');
// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; });
// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));
// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0
Sorting multidimensional array
// Sort multidimensional array (sort list of users by their names)
$users = [
array('name' => 'Robert', 'age' => 20),
array('name' => 'Alex', 'age' => 30),
array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));
// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key
Sorting array of objects
// 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
Sorting with a comparison function
// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');
// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
return chr($v1[0]) - chr($v2[0]);
});
You can see all these examples here.
add a comment |
up vote
0
down vote
There are several ways to sort an array.I will mention some methods for doing that task.fist of all , I will give an integer array which is called as '$numbers'.
$number = array(8,9,3,4,0,1,2);
This is the normal way to creating an array. Suppose that , I want to sort that array in ascending order.For that, 'sort()' method can be used.
<?php
$number = array(8,9,3,4,0,1,2);
sort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output of that,
You can see printed number array is sorted. If you want to that number array to be sort is descending order, 'rsort()' method can be use for that task.
<?php
$number = array(8,9,3,4,0,1,2);
rsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
consider the output..
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,
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
So ,Now I want to sort this array in ascending order according their value.'asort()' method can be used for that.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
asort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
If sorting descending order according their value,'arsort()' method can be used.
Suppose that you want to sort that array according their key value. In this , 'ksort()' method can be use.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
ksort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output.
Now array is sorted according their key value.If You want to sort the array in descending order according their key value,'krsort()' method can be used.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
krsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now associative array is sorted in descending order according their key value.Look at the output.
These are the some methods for sorting an array in ascending or descending order in php.I hope to you could get an idea.Thank you!
add a comment |
up vote
-1
down vote
The simplest is to use usort function to sort array without any looping :
Below is an example :
$array_compare= array("0" =>4,"1"=>2,"2"=>500,"3"=>100);
This will sort in desending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) > 0 ? 1 :-1;
});
This will sort in asending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) < 0 ? 1 :-1;
});
1
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
add a comment |
protected by deceze♦ Oct 28 '14 at 6:11
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).
Would you like to answer one of these unanswered questions instead?
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
139
down vote
accepted
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
$array = array(
array('foo' => 'bar', 'baz' => 42),
array('foo' => ..., 'baz' => ...),
...
);
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:
function cmp(array $a, array $b) {
if ($a['foo'] < $b['foo']) {
return -1;
} else if ($a['foo'] > $b['foo']) {
return 1;
} else {
return 0;
}
}
Often, you will want to use an anonymous function as the callback. If you want to use a method or static method, see the other ways of specifying a callback in PHP.
You then use one of these functions:
usort
uasort
uksort
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.
To get used to this idea, try this:
function cmp($a, $b) {
echo 'cmp called with $a:', PHP_EOL;
var_dump($a);
echo 'and $b:', PHP_EOL;
var_dump($b);
}
All you did was define a custom way to compare two items, that's all you need. That works with all sorts of values.
By the way, this works on any value, the values don't have to be complex arrays. If you have a custom comparison you want to do, you can do it on a simple array of numbers too.
sort
sorts by reference and does not return anything useful!
Note that the array sorts in place, you do not need to assign the return value to anything. $array = sort($array)
will replace the array with true
, not with a sorted array. Just sort($array);
works.
Custom numeric comparisons
If you want to sort by the baz
key, which is numeric, all you need to do is:
function cmp(array $a, array $b) {
return $a['baz'] - $b['baz'];
}
Thanks to The PoWEr oF MATH this returns a value < 0, 0 or > 0 depending on whether $a
is lower than, equal to or larger than $b
.
Note that this won't work well for float
values, since they'll be reduced to an int
and lose precision. Use explicit -1
, 0
and 1
return values instead.
Objects
If you have an array of objects, it works the same way:
function cmp($a, $b) {
return $a->baz - $b->baz;
}
Functions
You can do anything you need inside a comparison function, including calling functions:
function cmp(array $a, array $b) {
return someFunction($a['baz']) - someFunction($b['baz']);
}
Strings
A shortcut for the first string comparison version:
function cmp(array $a, array $b) {
return strcmp($a['foo'], $b['foo']);
}
strcmp
does exactly what's expected of cmp
here, it returns -1
, 0
or 1
.
Spaceship operator
PHP 7 introduced the spaceship operator, which unifies and simplifies equal/smaller/larger than comparisons across types:
function cmp(array $a, array $b) {
return $a['foo'] <=> $b['foo'];
}
Sorting by multiple fields
If you want to sort primarily by foo
, but if foo
is equal for two elements sort by baz
:
function cmp(array $a, array $b) {
if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
return $cmp;
} else {
return $a['baz'] - $b['baz'];
}
}
For those familiar, this is equivalent to an SQL query with ORDER BY foo, baz
.
Also see this very neat shorthand version and how to create such a comparison function dynamically for an arbitrary number of keys.
Sorting into a manual, static order
If you want to sort elements into a "manual order" like "foo", "bar", "baz":
function cmp(array $a, array $b) {
static $order = array('foo', 'bar', 'baz');
return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}
For all the above, if you're using PHP 5.3 or higher (and you really should), use anonymous functions for shorter code and to avoid having another global function floating around:
usort($array, function (array $a, array $b) { return $a['baz'] - $b['baz']; });
That's how simple sorting a complex multi-dimensional array can be. Again, just think in terms of teaching PHP how to tell which of two items is "greater"; let PHP do the actual sorting.
Also for all of the above, to switch between ascending and descending order simply swap the $a
and $b
arguments around. E.g.:
return $a['baz'] - $b['baz']; // ascending
return $b['baz'] - $a['baz']; // descending
Sorting one array based on another
And then there's the peculiar array_multisort
, which lets you sort one array based on another:
$array1 = array( 4, 6, 1);
$array2 = array('a', 'b', 'c');
The expected result here would be:
$array2 = array('c', 'a', 'b'); // the sorted order of $array1
Use array_multisort
to get there:
array_multisort($array1, $array2);
As of PHP 5.5.0 you can use array_column
to extract a column from a multi dimensional array and sort the array on that column:
array_multisort(array_column($array, 'foo'), SORT_DESC, $array);
As of PHP 7.0.0 you can also extract properties from an array of objects.
If you have more common cases, feel free to edit this answer.
The numeric comparison function doesn't work for float values; I'm sure you know what I mean :)
– Ja͢ck
Jun 28 '13 at 12:07
True, added a note.
– deceze♦
Jun 28 '13 at 12:09
1
For the static order, I would applyarray_flip()
to make use of speedier position lookup, e.g.$order[$a['foo']]
instead ofarray_search($a['foo'], $order)
.
– Ja͢ck
Jun 28 '13 at 23:58
Might be a bit of a big edit: gist.github.com/Rizier123/24a6248758b53245a63e839d8e08a32b but if you think it is an improvement and I included everything essential I can apply it.
– Rizier123
Jun 2 '16 at 16:30
@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
|
show 1 more comment
up vote
139
down vote
accepted
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
$array = array(
array('foo' => 'bar', 'baz' => 42),
array('foo' => ..., 'baz' => ...),
...
);
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:
function cmp(array $a, array $b) {
if ($a['foo'] < $b['foo']) {
return -1;
} else if ($a['foo'] > $b['foo']) {
return 1;
} else {
return 0;
}
}
Often, you will want to use an anonymous function as the callback. If you want to use a method or static method, see the other ways of specifying a callback in PHP.
You then use one of these functions:
usort
uasort
uksort
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.
To get used to this idea, try this:
function cmp($a, $b) {
echo 'cmp called with $a:', PHP_EOL;
var_dump($a);
echo 'and $b:', PHP_EOL;
var_dump($b);
}
All you did was define a custom way to compare two items, that's all you need. That works with all sorts of values.
By the way, this works on any value, the values don't have to be complex arrays. If you have a custom comparison you want to do, you can do it on a simple array of numbers too.
sort
sorts by reference and does not return anything useful!
Note that the array sorts in place, you do not need to assign the return value to anything. $array = sort($array)
will replace the array with true
, not with a sorted array. Just sort($array);
works.
Custom numeric comparisons
If you want to sort by the baz
key, which is numeric, all you need to do is:
function cmp(array $a, array $b) {
return $a['baz'] - $b['baz'];
}
Thanks to The PoWEr oF MATH this returns a value < 0, 0 or > 0 depending on whether $a
is lower than, equal to or larger than $b
.
Note that this won't work well for float
values, since they'll be reduced to an int
and lose precision. Use explicit -1
, 0
and 1
return values instead.
Objects
If you have an array of objects, it works the same way:
function cmp($a, $b) {
return $a->baz - $b->baz;
}
Functions
You can do anything you need inside a comparison function, including calling functions:
function cmp(array $a, array $b) {
return someFunction($a['baz']) - someFunction($b['baz']);
}
Strings
A shortcut for the first string comparison version:
function cmp(array $a, array $b) {
return strcmp($a['foo'], $b['foo']);
}
strcmp
does exactly what's expected of cmp
here, it returns -1
, 0
or 1
.
Spaceship operator
PHP 7 introduced the spaceship operator, which unifies and simplifies equal/smaller/larger than comparisons across types:
function cmp(array $a, array $b) {
return $a['foo'] <=> $b['foo'];
}
Sorting by multiple fields
If you want to sort primarily by foo
, but if foo
is equal for two elements sort by baz
:
function cmp(array $a, array $b) {
if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
return $cmp;
} else {
return $a['baz'] - $b['baz'];
}
}
For those familiar, this is equivalent to an SQL query with ORDER BY foo, baz
.
Also see this very neat shorthand version and how to create such a comparison function dynamically for an arbitrary number of keys.
Sorting into a manual, static order
If you want to sort elements into a "manual order" like "foo", "bar", "baz":
function cmp(array $a, array $b) {
static $order = array('foo', 'bar', 'baz');
return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}
For all the above, if you're using PHP 5.3 or higher (and you really should), use anonymous functions for shorter code and to avoid having another global function floating around:
usort($array, function (array $a, array $b) { return $a['baz'] - $b['baz']; });
That's how simple sorting a complex multi-dimensional array can be. Again, just think in terms of teaching PHP how to tell which of two items is "greater"; let PHP do the actual sorting.
Also for all of the above, to switch between ascending and descending order simply swap the $a
and $b
arguments around. E.g.:
return $a['baz'] - $b['baz']; // ascending
return $b['baz'] - $a['baz']; // descending
Sorting one array based on another
And then there's the peculiar array_multisort
, which lets you sort one array based on another:
$array1 = array( 4, 6, 1);
$array2 = array('a', 'b', 'c');
The expected result here would be:
$array2 = array('c', 'a', 'b'); // the sorted order of $array1
Use array_multisort
to get there:
array_multisort($array1, $array2);
As of PHP 5.5.0 you can use array_column
to extract a column from a multi dimensional array and sort the array on that column:
array_multisort(array_column($array, 'foo'), SORT_DESC, $array);
As of PHP 7.0.0 you can also extract properties from an array of objects.
If you have more common cases, feel free to edit this answer.
The numeric comparison function doesn't work for float values; I'm sure you know what I mean :)
– Ja͢ck
Jun 28 '13 at 12:07
True, added a note.
– deceze♦
Jun 28 '13 at 12:09
1
For the static order, I would applyarray_flip()
to make use of speedier position lookup, e.g.$order[$a['foo']]
instead ofarray_search($a['foo'], $order)
.
– Ja͢ck
Jun 28 '13 at 23:58
Might be a bit of a big edit: gist.github.com/Rizier123/24a6248758b53245a63e839d8e08a32b but if you think it is an improvement and I included everything essential I can apply it.
– Rizier123
Jun 2 '16 at 16:30
@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
|
show 1 more comment
up vote
139
down vote
accepted
up vote
139
down vote
accepted
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
$array = array(
array('foo' => 'bar', 'baz' => 42),
array('foo' => ..., 'baz' => ...),
...
);
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:
function cmp(array $a, array $b) {
if ($a['foo'] < $b['foo']) {
return -1;
} else if ($a['foo'] > $b['foo']) {
return 1;
} else {
return 0;
}
}
Often, you will want to use an anonymous function as the callback. If you want to use a method or static method, see the other ways of specifying a callback in PHP.
You then use one of these functions:
usort
uasort
uksort
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.
To get used to this idea, try this:
function cmp($a, $b) {
echo 'cmp called with $a:', PHP_EOL;
var_dump($a);
echo 'and $b:', PHP_EOL;
var_dump($b);
}
All you did was define a custom way to compare two items, that's all you need. That works with all sorts of values.
By the way, this works on any value, the values don't have to be complex arrays. If you have a custom comparison you want to do, you can do it on a simple array of numbers too.
sort
sorts by reference and does not return anything useful!
Note that the array sorts in place, you do not need to assign the return value to anything. $array = sort($array)
will replace the array with true
, not with a sorted array. Just sort($array);
works.
Custom numeric comparisons
If you want to sort by the baz
key, which is numeric, all you need to do is:
function cmp(array $a, array $b) {
return $a['baz'] - $b['baz'];
}
Thanks to The PoWEr oF MATH this returns a value < 0, 0 or > 0 depending on whether $a
is lower than, equal to or larger than $b
.
Note that this won't work well for float
values, since they'll be reduced to an int
and lose precision. Use explicit -1
, 0
and 1
return values instead.
Objects
If you have an array of objects, it works the same way:
function cmp($a, $b) {
return $a->baz - $b->baz;
}
Functions
You can do anything you need inside a comparison function, including calling functions:
function cmp(array $a, array $b) {
return someFunction($a['baz']) - someFunction($b['baz']);
}
Strings
A shortcut for the first string comparison version:
function cmp(array $a, array $b) {
return strcmp($a['foo'], $b['foo']);
}
strcmp
does exactly what's expected of cmp
here, it returns -1
, 0
or 1
.
Spaceship operator
PHP 7 introduced the spaceship operator, which unifies and simplifies equal/smaller/larger than comparisons across types:
function cmp(array $a, array $b) {
return $a['foo'] <=> $b['foo'];
}
Sorting by multiple fields
If you want to sort primarily by foo
, but if foo
is equal for two elements sort by baz
:
function cmp(array $a, array $b) {
if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
return $cmp;
} else {
return $a['baz'] - $b['baz'];
}
}
For those familiar, this is equivalent to an SQL query with ORDER BY foo, baz
.
Also see this very neat shorthand version and how to create such a comparison function dynamically for an arbitrary number of keys.
Sorting into a manual, static order
If you want to sort elements into a "manual order" like "foo", "bar", "baz":
function cmp(array $a, array $b) {
static $order = array('foo', 'bar', 'baz');
return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}
For all the above, if you're using PHP 5.3 or higher (and you really should), use anonymous functions for shorter code and to avoid having another global function floating around:
usort($array, function (array $a, array $b) { return $a['baz'] - $b['baz']; });
That's how simple sorting a complex multi-dimensional array can be. Again, just think in terms of teaching PHP how to tell which of two items is "greater"; let PHP do the actual sorting.
Also for all of the above, to switch between ascending and descending order simply swap the $a
and $b
arguments around. E.g.:
return $a['baz'] - $b['baz']; // ascending
return $b['baz'] - $a['baz']; // descending
Sorting one array based on another
And then there's the peculiar array_multisort
, which lets you sort one array based on another:
$array1 = array( 4, 6, 1);
$array2 = array('a', 'b', 'c');
The expected result here would be:
$array2 = array('c', 'a', 'b'); // the sorted order of $array1
Use array_multisort
to get there:
array_multisort($array1, $array2);
As of PHP 5.5.0 you can use array_column
to extract a column from a multi dimensional array and sort the array on that column:
array_multisort(array_column($array, 'foo'), SORT_DESC, $array);
As of PHP 7.0.0 you can also extract properties from an array of objects.
If you have more common cases, feel free to edit this answer.
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
$array = array(
array('foo' => 'bar', 'baz' => 42),
array('foo' => ..., 'baz' => ...),
...
);
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:
function cmp(array $a, array $b) {
if ($a['foo'] < $b['foo']) {
return -1;
} else if ($a['foo'] > $b['foo']) {
return 1;
} else {
return 0;
}
}
Often, you will want to use an anonymous function as the callback. If you want to use a method or static method, see the other ways of specifying a callback in PHP.
You then use one of these functions:
usort
uasort
uksort
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.
To get used to this idea, try this:
function cmp($a, $b) {
echo 'cmp called with $a:', PHP_EOL;
var_dump($a);
echo 'and $b:', PHP_EOL;
var_dump($b);
}
All you did was define a custom way to compare two items, that's all you need. That works with all sorts of values.
By the way, this works on any value, the values don't have to be complex arrays. If you have a custom comparison you want to do, you can do it on a simple array of numbers too.
sort
sorts by reference and does not return anything useful!
Note that the array sorts in place, you do not need to assign the return value to anything. $array = sort($array)
will replace the array with true
, not with a sorted array. Just sort($array);
works.
Custom numeric comparisons
If you want to sort by the baz
key, which is numeric, all you need to do is:
function cmp(array $a, array $b) {
return $a['baz'] - $b['baz'];
}
Thanks to The PoWEr oF MATH this returns a value < 0, 0 or > 0 depending on whether $a
is lower than, equal to or larger than $b
.
Note that this won't work well for float
values, since they'll be reduced to an int
and lose precision. Use explicit -1
, 0
and 1
return values instead.
Objects
If you have an array of objects, it works the same way:
function cmp($a, $b) {
return $a->baz - $b->baz;
}
Functions
You can do anything you need inside a comparison function, including calling functions:
function cmp(array $a, array $b) {
return someFunction($a['baz']) - someFunction($b['baz']);
}
Strings
A shortcut for the first string comparison version:
function cmp(array $a, array $b) {
return strcmp($a['foo'], $b['foo']);
}
strcmp
does exactly what's expected of cmp
here, it returns -1
, 0
or 1
.
Spaceship operator
PHP 7 introduced the spaceship operator, which unifies and simplifies equal/smaller/larger than comparisons across types:
function cmp(array $a, array $b) {
return $a['foo'] <=> $b['foo'];
}
Sorting by multiple fields
If you want to sort primarily by foo
, but if foo
is equal for two elements sort by baz
:
function cmp(array $a, array $b) {
if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
return $cmp;
} else {
return $a['baz'] - $b['baz'];
}
}
For those familiar, this is equivalent to an SQL query with ORDER BY foo, baz
.
Also see this very neat shorthand version and how to create such a comparison function dynamically for an arbitrary number of keys.
Sorting into a manual, static order
If you want to sort elements into a "manual order" like "foo", "bar", "baz":
function cmp(array $a, array $b) {
static $order = array('foo', 'bar', 'baz');
return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}
For all the above, if you're using PHP 5.3 or higher (and you really should), use anonymous functions for shorter code and to avoid having another global function floating around:
usort($array, function (array $a, array $b) { return $a['baz'] - $b['baz']; });
That's how simple sorting a complex multi-dimensional array can be. Again, just think in terms of teaching PHP how to tell which of two items is "greater"; let PHP do the actual sorting.
Also for all of the above, to switch between ascending and descending order simply swap the $a
and $b
arguments around. E.g.:
return $a['baz'] - $b['baz']; // ascending
return $b['baz'] - $a['baz']; // descending
Sorting one array based on another
And then there's the peculiar array_multisort
, which lets you sort one array based on another:
$array1 = array( 4, 6, 1);
$array2 = array('a', 'b', 'c');
The expected result here would be:
$array2 = array('c', 'a', 'b'); // the sorted order of $array1
Use array_multisort
to get there:
array_multisort($array1, $array2);
As of PHP 5.5.0 you can use array_column
to extract a column from a multi dimensional array and sort the array on that column:
array_multisort(array_column($array, 'foo'), SORT_DESC, $array);
As of PHP 7.0.0 you can also extract properties from an array of objects.
If you have more common cases, feel free to edit this answer.
edited Jan 24 at 16:30
answered Jun 28 '13 at 11:53
deceze♦
390k61529685
390k61529685
The numeric comparison function doesn't work for float values; I'm sure you know what I mean :)
– Ja͢ck
Jun 28 '13 at 12:07
True, added a note.
– deceze♦
Jun 28 '13 at 12:09
1
For the static order, I would applyarray_flip()
to make use of speedier position lookup, e.g.$order[$a['foo']]
instead ofarray_search($a['foo'], $order)
.
– Ja͢ck
Jun 28 '13 at 23:58
Might be a bit of a big edit: gist.github.com/Rizier123/24a6248758b53245a63e839d8e08a32b but if you think it is an improvement and I included everything essential I can apply it.
– Rizier123
Jun 2 '16 at 16:30
@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
|
show 1 more comment
The numeric comparison function doesn't work for float values; I'm sure you know what I mean :)
– Ja͢ck
Jun 28 '13 at 12:07
True, added a note.
– deceze♦
Jun 28 '13 at 12:09
1
For the static order, I would applyarray_flip()
to make use of speedier position lookup, e.g.$order[$a['foo']]
instead ofarray_search($a['foo'], $order)
.
– Ja͢ck
Jun 28 '13 at 23:58
Might be a bit of a big edit: gist.github.com/Rizier123/24a6248758b53245a63e839d8e08a32b but if you think it is an improvement and I included everything essential I can apply it.
– Rizier123
Jun 2 '16 at 16:30
@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
The numeric comparison function doesn't work for float values; I'm sure you know what I mean :)
– Ja͢ck
Jun 28 '13 at 12:07
The numeric comparison function doesn't work for float values; I'm sure you know what I mean :)
– Ja͢ck
Jun 28 '13 at 12:07
True, added a note.
– deceze♦
Jun 28 '13 at 12:09
True, added a note.
– deceze♦
Jun 28 '13 at 12:09
1
1
For the static order, I would apply
array_flip()
to make use of speedier position lookup, e.g. $order[$a['foo']]
instead of array_search($a['foo'], $order)
.– Ja͢ck
Jun 28 '13 at 23:58
For the static order, I would apply
array_flip()
to make use of speedier position lookup, e.g. $order[$a['foo']]
instead of array_search($a['foo'], $order)
.– Ja͢ck
Jun 28 '13 at 23:58
Might be a bit of a big edit: gist.github.com/Rizier123/24a6248758b53245a63e839d8e08a32b but if you think it is an improvement and I included everything essential I can apply it.
– Rizier123
Jun 2 '16 at 16:30
Might be a bit of a big edit: gist.github.com/Rizier123/24a6248758b53245a63e839d8e08a32b but if you think it is an improvement and I included everything essential I can apply it.
– Rizier123
Jun 2 '16 at 16:30
@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
@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
|
show 1 more comment
up vote
135
down vote
Well most basic methods are already covered by deceze I would try to look at other types of sort
Sorting with SPL
SplHeap
class SimpleHeapSort extends SplHeap {
public function compare($a, $b) {
return strcmp($a, $b);
}
}
// Let's populate our heap here (data of 2009)
$heap = new SimpleHeapSort();
$heap->insert("a");
$heap->insert("b");
$heap->insert("c");
echo implode(PHP_EOL, iterator_to_array($heap));
Output
c
b
a
SplMaxHeap
The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.
$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(2);
$heap->insert(3);
SplMinHeap
The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.
$heap = new SplMinHeap ();
$heap->insert(3);
$heap->insert(1);
$heap->insert(2);
Other Types of Sort
Bubble Sort
From the Wikipedia article on 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.
function bubbleSort(array $array) {
$array_size = count($array);
for($i = 0; $i < $array_size; $i ++) {
for($j = 0; $j < $array_size; $j ++) {
if ($array[$i] < $array[$j]) {
$tem = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tem;
}
}
}
return $array;
}
Selection sort
From the Wikipedia article on 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.
function selectionSort(array $array) {
$length = count($array);
for($i = 0; $i < $length; $i ++) {
$min = $i;
for($j = $i + 1; $j < $length; $j ++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$tmp = $array[$min];
$array[$min] = $array[$i];
$array[$i] = $tmp;
}
return $array;
}
Insertion sort
From the Wikipedia article on 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:
function insertionSort(array $array) {
$count = count($array);
for($i = 1; $i < $count; $i ++) {
$j = $i - 1;
// second element of the array
$element = $array[$i];
while ( $j >= 0 && $array[$j] > $element ) {
$array[$j + 1] = $array[$j];
$array[$j] = $element;
$j = $j - 1;
}
}
return $array;
}
Shellsort
From the Wikipedia article on 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.
function shellSort(array $array) {
$gaps = array(
1,
2,
3,
4,
6
);
$gap = array_pop($gaps);
$length = count($array);
while ( $gap > 0 ) {
for($i = $gap; $i < $length; $i ++) {
$tmp = $array[$i];
$j = $i;
while ( $j >= $gap && $array[$j - $gap] > $tmp ) {
$array[$j] = $array[$j - $gap];
$j -= $gap;
}
$array[$j] = $tmp;
}
$gap = array_pop($gaps);
}
return $array;
}
Comb sort
From the Wikipedia article on 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.
function combSort(array $array) {
$gap = count($array);
$swap = true;
while ( $gap > 1 || $swap ) {
if ($gap > 1)
$gap /= 1.25;
$swap = false;
$i = 0;
while ( $i + $gap < count($array) ) {
if ($array[$i] > $array[$i + $gap]) {
// swapping the elements.
list($array[$i], $array[$i + $gap]) = array(
$array[$i + $gap],
$array[$i]
);
$swap = true;
}
$i ++;
}
}
return $array;
}
Merge sort
From the Wikipedia article on 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
function mergeSort(array $array) {
if (count($array) <= 1)
return $array;
$left = mergeSort(array_splice($array, floor(count($array) / 2)));
$right = mergeSort($array);
$result = array();
while ( count($left) > 0 && count($right) > 0 ) {
if ($left[0] <= $right[0]) {
array_push($result, array_shift($left));
} else {
array_push($result, array_shift($right));
}
}
while ( count($left) > 0 )
array_push($result, array_shift($left));
while ( count($right) > 0 )
array_push($result, array_shift($right));
return $result;
}
Quicksort
From the Wikipedia article on 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.
function quickSort(array $array) {
if (count($array) == 0) {
return $array;
}
$pivot = $array[0];
$left = $right = array();
for($i = 1; $i < count($array); $i ++) {
if ($array[$i] < $pivot) {
$left = $array[$i];
} else {
$right = $array[$i];
}
}
return array_merge(quickSort($left), array(
$pivot
), quickSort($right));
}
Permutation sort
From the Wikipedia article on Permutation sort:
Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one.
function permutationSort($items, $perms = array()) {
if (empty($items)) {
if (inOrder($perms)) {
return $perms;
}
} else {
for($i = count($items) - 1; $i >= 0; -- $i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permutationSort($newitems, $newperms);
if ($res) {
return $res;
}
}
}
}
function inOrder($array) {
for($i = 0; $i < count($array); $i ++) {
if (isset($array[$i + 1])) {
if ($array[$i] > $array[$i + 1]) {
return False;
}
}
}
return True;
}
Radix sort
From the Wikipedia article on 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.
// Radix Sort for 0 to 256
function radixSort($array) {
$n = count($array);
$partition = array();
for($slot = 0; $slot < 256; ++ $slot) {
$partition = array();
}
for($i = 0; $i < $n; ++ $i) {
$partition[$array[$i]->age & 0xFF] = &$array[$i];
}
$i = 0;
for($slot = 0; $slot < 256; ++ $slot) {
for($j = 0, $n = count($partition[$slot]); $j < $n; ++ $j) {
$array[$i ++] = &$partition[$slot][$j];
}
}
return $array;
}
4
@deceze you covered all the basics .. i had to look for another way to be relevant :)
– Baba
Jun 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
– Dave
Jun 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 causesO(n^2)
comparisons if we'll use just first element as pivot)
– Alma Do
May 3 '14 at 21:10
I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuq
Jan 13 '16 at 10:18
I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike Nguyen
Mar 10 '16 at 4:03
add a comment |
up vote
135
down vote
Well most basic methods are already covered by deceze I would try to look at other types of sort
Sorting with SPL
SplHeap
class SimpleHeapSort extends SplHeap {
public function compare($a, $b) {
return strcmp($a, $b);
}
}
// Let's populate our heap here (data of 2009)
$heap = new SimpleHeapSort();
$heap->insert("a");
$heap->insert("b");
$heap->insert("c");
echo implode(PHP_EOL, iterator_to_array($heap));
Output
c
b
a
SplMaxHeap
The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.
$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(2);
$heap->insert(3);
SplMinHeap
The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.
$heap = new SplMinHeap ();
$heap->insert(3);
$heap->insert(1);
$heap->insert(2);
Other Types of Sort
Bubble Sort
From the Wikipedia article on 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.
function bubbleSort(array $array) {
$array_size = count($array);
for($i = 0; $i < $array_size; $i ++) {
for($j = 0; $j < $array_size; $j ++) {
if ($array[$i] < $array[$j]) {
$tem = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tem;
}
}
}
return $array;
}
Selection sort
From the Wikipedia article on 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.
function selectionSort(array $array) {
$length = count($array);
for($i = 0; $i < $length; $i ++) {
$min = $i;
for($j = $i + 1; $j < $length; $j ++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$tmp = $array[$min];
$array[$min] = $array[$i];
$array[$i] = $tmp;
}
return $array;
}
Insertion sort
From the Wikipedia article on 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:
function insertionSort(array $array) {
$count = count($array);
for($i = 1; $i < $count; $i ++) {
$j = $i - 1;
// second element of the array
$element = $array[$i];
while ( $j >= 0 && $array[$j] > $element ) {
$array[$j + 1] = $array[$j];
$array[$j] = $element;
$j = $j - 1;
}
}
return $array;
}
Shellsort
From the Wikipedia article on 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.
function shellSort(array $array) {
$gaps = array(
1,
2,
3,
4,
6
);
$gap = array_pop($gaps);
$length = count($array);
while ( $gap > 0 ) {
for($i = $gap; $i < $length; $i ++) {
$tmp = $array[$i];
$j = $i;
while ( $j >= $gap && $array[$j - $gap] > $tmp ) {
$array[$j] = $array[$j - $gap];
$j -= $gap;
}
$array[$j] = $tmp;
}
$gap = array_pop($gaps);
}
return $array;
}
Comb sort
From the Wikipedia article on 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.
function combSort(array $array) {
$gap = count($array);
$swap = true;
while ( $gap > 1 || $swap ) {
if ($gap > 1)
$gap /= 1.25;
$swap = false;
$i = 0;
while ( $i + $gap < count($array) ) {
if ($array[$i] > $array[$i + $gap]) {
// swapping the elements.
list($array[$i], $array[$i + $gap]) = array(
$array[$i + $gap],
$array[$i]
);
$swap = true;
}
$i ++;
}
}
return $array;
}
Merge sort
From the Wikipedia article on 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
function mergeSort(array $array) {
if (count($array) <= 1)
return $array;
$left = mergeSort(array_splice($array, floor(count($array) / 2)));
$right = mergeSort($array);
$result = array();
while ( count($left) > 0 && count($right) > 0 ) {
if ($left[0] <= $right[0]) {
array_push($result, array_shift($left));
} else {
array_push($result, array_shift($right));
}
}
while ( count($left) > 0 )
array_push($result, array_shift($left));
while ( count($right) > 0 )
array_push($result, array_shift($right));
return $result;
}
Quicksort
From the Wikipedia article on 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.
function quickSort(array $array) {
if (count($array) == 0) {
return $array;
}
$pivot = $array[0];
$left = $right = array();
for($i = 1; $i < count($array); $i ++) {
if ($array[$i] < $pivot) {
$left = $array[$i];
} else {
$right = $array[$i];
}
}
return array_merge(quickSort($left), array(
$pivot
), quickSort($right));
}
Permutation sort
From the Wikipedia article on Permutation sort:
Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one.
function permutationSort($items, $perms = array()) {
if (empty($items)) {
if (inOrder($perms)) {
return $perms;
}
} else {
for($i = count($items) - 1; $i >= 0; -- $i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permutationSort($newitems, $newperms);
if ($res) {
return $res;
}
}
}
}
function inOrder($array) {
for($i = 0; $i < count($array); $i ++) {
if (isset($array[$i + 1])) {
if ($array[$i] > $array[$i + 1]) {
return False;
}
}
}
return True;
}
Radix sort
From the Wikipedia article on 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.
// Radix Sort for 0 to 256
function radixSort($array) {
$n = count($array);
$partition = array();
for($slot = 0; $slot < 256; ++ $slot) {
$partition = array();
}
for($i = 0; $i < $n; ++ $i) {
$partition[$array[$i]->age & 0xFF] = &$array[$i];
}
$i = 0;
for($slot = 0; $slot < 256; ++ $slot) {
for($j = 0, $n = count($partition[$slot]); $j < $n; ++ $j) {
$array[$i ++] = &$partition[$slot][$j];
}
}
return $array;
}
4
@deceze you covered all the basics .. i had to look for another way to be relevant :)
– Baba
Jun 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
– Dave
Jun 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 causesO(n^2)
comparisons if we'll use just first element as pivot)
– Alma Do
May 3 '14 at 21:10
I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuq
Jan 13 '16 at 10:18
I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike Nguyen
Mar 10 '16 at 4:03
add a comment |
up vote
135
down vote
up vote
135
down vote
Well most basic methods are already covered by deceze I would try to look at other types of sort
Sorting with SPL
SplHeap
class SimpleHeapSort extends SplHeap {
public function compare($a, $b) {
return strcmp($a, $b);
}
}
// Let's populate our heap here (data of 2009)
$heap = new SimpleHeapSort();
$heap->insert("a");
$heap->insert("b");
$heap->insert("c");
echo implode(PHP_EOL, iterator_to_array($heap));
Output
c
b
a
SplMaxHeap
The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.
$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(2);
$heap->insert(3);
SplMinHeap
The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.
$heap = new SplMinHeap ();
$heap->insert(3);
$heap->insert(1);
$heap->insert(2);
Other Types of Sort
Bubble Sort
From the Wikipedia article on 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.
function bubbleSort(array $array) {
$array_size = count($array);
for($i = 0; $i < $array_size; $i ++) {
for($j = 0; $j < $array_size; $j ++) {
if ($array[$i] < $array[$j]) {
$tem = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tem;
}
}
}
return $array;
}
Selection sort
From the Wikipedia article on 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.
function selectionSort(array $array) {
$length = count($array);
for($i = 0; $i < $length; $i ++) {
$min = $i;
for($j = $i + 1; $j < $length; $j ++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$tmp = $array[$min];
$array[$min] = $array[$i];
$array[$i] = $tmp;
}
return $array;
}
Insertion sort
From the Wikipedia article on 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:
function insertionSort(array $array) {
$count = count($array);
for($i = 1; $i < $count; $i ++) {
$j = $i - 1;
// second element of the array
$element = $array[$i];
while ( $j >= 0 && $array[$j] > $element ) {
$array[$j + 1] = $array[$j];
$array[$j] = $element;
$j = $j - 1;
}
}
return $array;
}
Shellsort
From the Wikipedia article on 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.
function shellSort(array $array) {
$gaps = array(
1,
2,
3,
4,
6
);
$gap = array_pop($gaps);
$length = count($array);
while ( $gap > 0 ) {
for($i = $gap; $i < $length; $i ++) {
$tmp = $array[$i];
$j = $i;
while ( $j >= $gap && $array[$j - $gap] > $tmp ) {
$array[$j] = $array[$j - $gap];
$j -= $gap;
}
$array[$j] = $tmp;
}
$gap = array_pop($gaps);
}
return $array;
}
Comb sort
From the Wikipedia article on 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.
function combSort(array $array) {
$gap = count($array);
$swap = true;
while ( $gap > 1 || $swap ) {
if ($gap > 1)
$gap /= 1.25;
$swap = false;
$i = 0;
while ( $i + $gap < count($array) ) {
if ($array[$i] > $array[$i + $gap]) {
// swapping the elements.
list($array[$i], $array[$i + $gap]) = array(
$array[$i + $gap],
$array[$i]
);
$swap = true;
}
$i ++;
}
}
return $array;
}
Merge sort
From the Wikipedia article on 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
function mergeSort(array $array) {
if (count($array) <= 1)
return $array;
$left = mergeSort(array_splice($array, floor(count($array) / 2)));
$right = mergeSort($array);
$result = array();
while ( count($left) > 0 && count($right) > 0 ) {
if ($left[0] <= $right[0]) {
array_push($result, array_shift($left));
} else {
array_push($result, array_shift($right));
}
}
while ( count($left) > 0 )
array_push($result, array_shift($left));
while ( count($right) > 0 )
array_push($result, array_shift($right));
return $result;
}
Quicksort
From the Wikipedia article on 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.
function quickSort(array $array) {
if (count($array) == 0) {
return $array;
}
$pivot = $array[0];
$left = $right = array();
for($i = 1; $i < count($array); $i ++) {
if ($array[$i] < $pivot) {
$left = $array[$i];
} else {
$right = $array[$i];
}
}
return array_merge(quickSort($left), array(
$pivot
), quickSort($right));
}
Permutation sort
From the Wikipedia article on Permutation sort:
Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one.
function permutationSort($items, $perms = array()) {
if (empty($items)) {
if (inOrder($perms)) {
return $perms;
}
} else {
for($i = count($items) - 1; $i >= 0; -- $i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permutationSort($newitems, $newperms);
if ($res) {
return $res;
}
}
}
}
function inOrder($array) {
for($i = 0; $i < count($array); $i ++) {
if (isset($array[$i + 1])) {
if ($array[$i] > $array[$i + 1]) {
return False;
}
}
}
return True;
}
Radix sort
From the Wikipedia article on 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.
// Radix Sort for 0 to 256
function radixSort($array) {
$n = count($array);
$partition = array();
for($slot = 0; $slot < 256; ++ $slot) {
$partition = array();
}
for($i = 0; $i < $n; ++ $i) {
$partition[$array[$i]->age & 0xFF] = &$array[$i];
}
$i = 0;
for($slot = 0; $slot < 256; ++ $slot) {
for($j = 0, $n = count($partition[$slot]); $j < $n; ++ $j) {
$array[$i ++] = &$partition[$slot][$j];
}
}
return $array;
}
Well most basic methods are already covered by deceze I would try to look at other types of sort
Sorting with SPL
SplHeap
class SimpleHeapSort extends SplHeap {
public function compare($a, $b) {
return strcmp($a, $b);
}
}
// Let's populate our heap here (data of 2009)
$heap = new SimpleHeapSort();
$heap->insert("a");
$heap->insert("b");
$heap->insert("c");
echo implode(PHP_EOL, iterator_to_array($heap));
Output
c
b
a
SplMaxHeap
The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.
$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(2);
$heap->insert(3);
SplMinHeap
The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.
$heap = new SplMinHeap ();
$heap->insert(3);
$heap->insert(1);
$heap->insert(2);
Other Types of Sort
Bubble Sort
From the Wikipedia article on 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.
function bubbleSort(array $array) {
$array_size = count($array);
for($i = 0; $i < $array_size; $i ++) {
for($j = 0; $j < $array_size; $j ++) {
if ($array[$i] < $array[$j]) {
$tem = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tem;
}
}
}
return $array;
}
Selection sort
From the Wikipedia article on 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.
function selectionSort(array $array) {
$length = count($array);
for($i = 0; $i < $length; $i ++) {
$min = $i;
for($j = $i + 1; $j < $length; $j ++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$tmp = $array[$min];
$array[$min] = $array[$i];
$array[$i] = $tmp;
}
return $array;
}
Insertion sort
From the Wikipedia article on 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:
function insertionSort(array $array) {
$count = count($array);
for($i = 1; $i < $count; $i ++) {
$j = $i - 1;
// second element of the array
$element = $array[$i];
while ( $j >= 0 && $array[$j] > $element ) {
$array[$j + 1] = $array[$j];
$array[$j] = $element;
$j = $j - 1;
}
}
return $array;
}
Shellsort
From the Wikipedia article on 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.
function shellSort(array $array) {
$gaps = array(
1,
2,
3,
4,
6
);
$gap = array_pop($gaps);
$length = count($array);
while ( $gap > 0 ) {
for($i = $gap; $i < $length; $i ++) {
$tmp = $array[$i];
$j = $i;
while ( $j >= $gap && $array[$j - $gap] > $tmp ) {
$array[$j] = $array[$j - $gap];
$j -= $gap;
}
$array[$j] = $tmp;
}
$gap = array_pop($gaps);
}
return $array;
}
Comb sort
From the Wikipedia article on 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.
function combSort(array $array) {
$gap = count($array);
$swap = true;
while ( $gap > 1 || $swap ) {
if ($gap > 1)
$gap /= 1.25;
$swap = false;
$i = 0;
while ( $i + $gap < count($array) ) {
if ($array[$i] > $array[$i + $gap]) {
// swapping the elements.
list($array[$i], $array[$i + $gap]) = array(
$array[$i + $gap],
$array[$i]
);
$swap = true;
}
$i ++;
}
}
return $array;
}
Merge sort
From the Wikipedia article on 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
function mergeSort(array $array) {
if (count($array) <= 1)
return $array;
$left = mergeSort(array_splice($array, floor(count($array) / 2)));
$right = mergeSort($array);
$result = array();
while ( count($left) > 0 && count($right) > 0 ) {
if ($left[0] <= $right[0]) {
array_push($result, array_shift($left));
} else {
array_push($result, array_shift($right));
}
}
while ( count($left) > 0 )
array_push($result, array_shift($left));
while ( count($right) > 0 )
array_push($result, array_shift($right));
return $result;
}
Quicksort
From the Wikipedia article on 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.
function quickSort(array $array) {
if (count($array) == 0) {
return $array;
}
$pivot = $array[0];
$left = $right = array();
for($i = 1; $i < count($array); $i ++) {
if ($array[$i] < $pivot) {
$left = $array[$i];
} else {
$right = $array[$i];
}
}
return array_merge(quickSort($left), array(
$pivot
), quickSort($right));
}
Permutation sort
From the Wikipedia article on Permutation sort:
Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one.
function permutationSort($items, $perms = array()) {
if (empty($items)) {
if (inOrder($perms)) {
return $perms;
}
} else {
for($i = count($items) - 1; $i >= 0; -- $i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permutationSort($newitems, $newperms);
if ($res) {
return $res;
}
}
}
}
function inOrder($array) {
for($i = 0; $i < count($array); $i ++) {
if (isset($array[$i + 1])) {
if ($array[$i] > $array[$i + 1]) {
return False;
}
}
}
return True;
}
Radix sort
From the Wikipedia article on 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.
// Radix Sort for 0 to 256
function radixSort($array) {
$n = count($array);
$partition = array();
for($slot = 0; $slot < 256; ++ $slot) {
$partition = array();
}
for($i = 0; $i < $n; ++ $i) {
$partition[$array[$i]->age & 0xFF] = &$array[$i];
}
$i = 0;
for($slot = 0; $slot < 256; ++ $slot) {
for($j = 0, $n = count($partition[$slot]); $j < $n; ++ $j) {
$array[$i ++] = &$partition[$slot][$j];
}
}
return $array;
}
edited May 23 '17 at 12:10
Community♦
11
11
answered Jun 28 '13 at 12:11
Baba
78.4k20130193
78.4k20130193
4
@deceze you covered all the basics .. i had to look for another way to be relevant :)
– Baba
Jun 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
– Dave
Jun 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 causesO(n^2)
comparisons if we'll use just first element as pivot)
– Alma Do
May 3 '14 at 21:10
I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuq
Jan 13 '16 at 10:18
I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike Nguyen
Mar 10 '16 at 4:03
add a comment |
4
@deceze you covered all the basics .. i had to look for another way to be relevant :)
– Baba
Jun 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
– Dave
Jun 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 causesO(n^2)
comparisons if we'll use just first element as pivot)
– Alma Do
May 3 '14 at 21:10
I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuq
Jan 13 '16 at 10:18
I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike Nguyen
Mar 10 '16 at 4:03
4
4
@deceze you covered all the basics .. i had to look for another way to be relevant :)
– Baba
Jun 28 '13 at 12:18
@deceze you covered all the basics .. i had to look for another way to be relevant :)
– Baba
Jun 28 '13 at 12:18
5
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
– Dave
Jun 28 '13 at 12:18
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
– Dave
Jun 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 Do
May 3 '14 at 21:10
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 Do
May 3 '14 at 21:10
I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuq
Jan 13 '16 at 10:18
I have heard that spl work faster than normal array sorting .Is it right?
– jewelhuq
Jan 13 '16 at 10:18
I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike Nguyen
Mar 10 '16 at 4:03
I agree with Dave, nowadays, almost fw have included that why I rarely remember or use it.
– Mike Nguyen
Mar 10 '16 at 4:03
add a comment |
up vote
43
down vote
Stable sort
Let's say you have an array like this:
['Kale', 'Kaleidoscope', 'Aardvark', 'Apple', 'Leicester', 'Lovely']
And now you want to sort on the first letter only:
usort($array, function($a, $b) {
return strcmp($a[0], $b[0]);
});
The outcome is this:
['Apple', 'Aardvark', 'Kale', 'Kaleidoscope', 'Lovely', 'Leicester']
The sort wasn't stable!
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):
array_walk($array, function(&$element, $index) {
$element = array($element, $index); // decorate
});
This transforms the array into this:
[
['Kale', 0], ['Kaleidoscope', 1],
['Aardvark', 2], ['Apple', 3],
['Leicester', 4], ['Lovely', 5]
]
Now, we adjust the comparison step; we compare the first letter again, but if they're the same, the secondary key is used to retain the original ordering:
usort($array, function($a, $b) {
// $a[0] and $b[0] contain the primary sort key
// $a[1] and $b[1] contain the secondary sort key
$tmp = strcmp($a[0][0], $b[0][0]);
if ($tmp != 0) {
return $tmp; // use primary key comparison results
}
return $a[1] - $b[1]; // use secondary key
});
Afterwards, we undecorate:
array_walk($array, function(&$element) {
$element = $element[0];
});
The final result:
['Aardvark', 'Apple', 'Kale', 'Kaleidoscope', 'Leicester', 'Lovely']
What about reuse?
You had to rewrite your comparison function to work with the transformed array elements; you may not want to edit your delicate comparison functions, so here's a wrapper for the comparison function:
function stablecmp($fn)
{
return function($a, $b) use ($fn) {
if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
return $tmp;
} else {
return $a[1] - $b[1];
}
};
}
Let's write the sort step using this function:
usort($array, stablecmp(function($a, $b) {
return strcmp($a[0], $b[0]);
}));
Voila! Your pristine comparison code is back.
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 Collier
Mar 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͢ck
Mar 2 '15 at 5:49
add a comment |
up vote
43
down vote
Stable sort
Let's say you have an array like this:
['Kale', 'Kaleidoscope', 'Aardvark', 'Apple', 'Leicester', 'Lovely']
And now you want to sort on the first letter only:
usort($array, function($a, $b) {
return strcmp($a[0], $b[0]);
});
The outcome is this:
['Apple', 'Aardvark', 'Kale', 'Kaleidoscope', 'Lovely', 'Leicester']
The sort wasn't stable!
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):
array_walk($array, function(&$element, $index) {
$element = array($element, $index); // decorate
});
This transforms the array into this:
[
['Kale', 0], ['Kaleidoscope', 1],
['Aardvark', 2], ['Apple', 3],
['Leicester', 4], ['Lovely', 5]
]
Now, we adjust the comparison step; we compare the first letter again, but if they're the same, the secondary key is used to retain the original ordering:
usort($array, function($a, $b) {
// $a[0] and $b[0] contain the primary sort key
// $a[1] and $b[1] contain the secondary sort key
$tmp = strcmp($a[0][0], $b[0][0]);
if ($tmp != 0) {
return $tmp; // use primary key comparison results
}
return $a[1] - $b[1]; // use secondary key
});
Afterwards, we undecorate:
array_walk($array, function(&$element) {
$element = $element[0];
});
The final result:
['Aardvark', 'Apple', 'Kale', 'Kaleidoscope', 'Leicester', 'Lovely']
What about reuse?
You had to rewrite your comparison function to work with the transformed array elements; you may not want to edit your delicate comparison functions, so here's a wrapper for the comparison function:
function stablecmp($fn)
{
return function($a, $b) use ($fn) {
if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
return $tmp;
} else {
return $a[1] - $b[1];
}
};
}
Let's write the sort step using this function:
usort($array, stablecmp(function($a, $b) {
return strcmp($a[0], $b[0]);
}));
Voila! Your pristine comparison code is back.
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 Collier
Mar 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͢ck
Mar 2 '15 at 5:49
add a comment |
up vote
43
down vote
up vote
43
down vote
Stable sort
Let's say you have an array like this:
['Kale', 'Kaleidoscope', 'Aardvark', 'Apple', 'Leicester', 'Lovely']
And now you want to sort on the first letter only:
usort($array, function($a, $b) {
return strcmp($a[0], $b[0]);
});
The outcome is this:
['Apple', 'Aardvark', 'Kale', 'Kaleidoscope', 'Lovely', 'Leicester']
The sort wasn't stable!
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):
array_walk($array, function(&$element, $index) {
$element = array($element, $index); // decorate
});
This transforms the array into this:
[
['Kale', 0], ['Kaleidoscope', 1],
['Aardvark', 2], ['Apple', 3],
['Leicester', 4], ['Lovely', 5]
]
Now, we adjust the comparison step; we compare the first letter again, but if they're the same, the secondary key is used to retain the original ordering:
usort($array, function($a, $b) {
// $a[0] and $b[0] contain the primary sort key
// $a[1] and $b[1] contain the secondary sort key
$tmp = strcmp($a[0][0], $b[0][0]);
if ($tmp != 0) {
return $tmp; // use primary key comparison results
}
return $a[1] - $b[1]; // use secondary key
});
Afterwards, we undecorate:
array_walk($array, function(&$element) {
$element = $element[0];
});
The final result:
['Aardvark', 'Apple', 'Kale', 'Kaleidoscope', 'Leicester', 'Lovely']
What about reuse?
You had to rewrite your comparison function to work with the transformed array elements; you may not want to edit your delicate comparison functions, so here's a wrapper for the comparison function:
function stablecmp($fn)
{
return function($a, $b) use ($fn) {
if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
return $tmp;
} else {
return $a[1] - $b[1];
}
};
}
Let's write the sort step using this function:
usort($array, stablecmp(function($a, $b) {
return strcmp($a[0], $b[0]);
}));
Voila! Your pristine comparison code is back.
Stable sort
Let's say you have an array like this:
['Kale', 'Kaleidoscope', 'Aardvark', 'Apple', 'Leicester', 'Lovely']
And now you want to sort on the first letter only:
usort($array, function($a, $b) {
return strcmp($a[0], $b[0]);
});
The outcome is this:
['Apple', 'Aardvark', 'Kale', 'Kaleidoscope', 'Lovely', 'Leicester']
The sort wasn't stable!
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):
array_walk($array, function(&$element, $index) {
$element = array($element, $index); // decorate
});
This transforms the array into this:
[
['Kale', 0], ['Kaleidoscope', 1],
['Aardvark', 2], ['Apple', 3],
['Leicester', 4], ['Lovely', 5]
]
Now, we adjust the comparison step; we compare the first letter again, but if they're the same, the secondary key is used to retain the original ordering:
usort($array, function($a, $b) {
// $a[0] and $b[0] contain the primary sort key
// $a[1] and $b[1] contain the secondary sort key
$tmp = strcmp($a[0][0], $b[0][0]);
if ($tmp != 0) {
return $tmp; // use primary key comparison results
}
return $a[1] - $b[1]; // use secondary key
});
Afterwards, we undecorate:
array_walk($array, function(&$element) {
$element = $element[0];
});
The final result:
['Aardvark', 'Apple', 'Kale', 'Kaleidoscope', 'Leicester', 'Lovely']
What about reuse?
You had to rewrite your comparison function to work with the transformed array elements; you may not want to edit your delicate comparison functions, so here's a wrapper for the comparison function:
function stablecmp($fn)
{
return function($a, $b) use ($fn) {
if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
return $tmp;
} else {
return $a[1] - $b[1];
}
};
}
Let's write the sort step using this function:
usort($array, stablecmp(function($a, $b) {
return strcmp($a[0], $b[0]);
}));
Voila! Your pristine comparison code is back.
edited Jun 28 '13 at 13:39
answered Jun 28 '13 at 13:05
Ja͢ck
143k25209264
143k25209264
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 Collier
Mar 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͢ck
Mar 2 '15 at 5:49
add a comment |
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 Collier
Mar 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͢ck
Mar 2 '15 at 5:49
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 Collier
Mar 2 '15 at 5:44
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 Collier
Mar 2 '15 at 5:44
1
1
@TylerCollier Yeah, you need to read between the lines of that Wikipedia reference ... I saved you the trouble of doing that ;-)
– Ja͢ck
Mar 2 '15 at 5:49
@TylerCollier Yeah, you need to read between the lines of that Wikipedia reference ... I saved you the trouble of doing that ;-)
– Ja͢ck
Mar 2 '15 at 5:49
add a comment |
up vote
15
down vote
As of PHP 5.3 with closures it is also possible to use a closure to determine the order of your sort.
For example assuming $array is an array of objects that contain a month property.
$orderArray = array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");
usort($array, function($a, $b) use ($orderArray){
return array_search($a->month, $orderArray) - array_search($b->month, $orderArray);
});
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 Langley
Jul 8 '14 at 18:33
add a comment |
up vote
15
down vote
As of PHP 5.3 with closures it is also possible to use a closure to determine the order of your sort.
For example assuming $array is an array of objects that contain a month property.
$orderArray = array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");
usort($array, function($a, $b) use ($orderArray){
return array_search($a->month, $orderArray) - array_search($b->month, $orderArray);
});
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 Langley
Jul 8 '14 at 18:33
add a comment |
up vote
15
down vote
up vote
15
down vote
As of PHP 5.3 with closures it is also possible to use a closure to determine the order of your sort.
For example assuming $array is an array of objects that contain a month property.
$orderArray = array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");
usort($array, function($a, $b) use ($orderArray){
return array_search($a->month, $orderArray) - array_search($b->month, $orderArray);
});
As of PHP 5.3 with closures it is also possible to use a closure to determine the order of your sort.
For example assuming $array is an array of objects that contain a month property.
$orderArray = array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");
usort($array, function($a, $b) use ($orderArray){
return array_search($a->month, $orderArray) - array_search($b->month, $orderArray);
});
edited Oct 29 '13 at 17:05
Danack
18.3k864100
18.3k864100
answered Aug 19 '13 at 19:16
Orangepill
22.6k33255
22.6k33255
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 Langley
Jul 8 '14 at 18:33
add a comment |
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 Langley
Jul 8 '14 at 18:33
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 Langley
Jul 8 '14 at 18:33
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 Langley
Jul 8 '14 at 18:33
add a comment |
up vote
9
down vote
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.
$sortedByName = from($objects)->orderBy('$v->name');
$sortedByCount = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
Comparisons can be further customized by passing a callback as a second argument, for example:
$sortedByFilenameNat = from($objects)->orderBy('$v->filename', 'strnatcmp');
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.
Internally, orderBy
and related methods call appropriate array sorting functions (uasort
, krsort
, multisort
, usort
etc.).
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
add a comment |
up vote
9
down vote
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.
$sortedByName = from($objects)->orderBy('$v->name');
$sortedByCount = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
Comparisons can be further customized by passing a callback as a second argument, for example:
$sortedByFilenameNat = from($objects)->orderBy('$v->filename', 'strnatcmp');
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.
Internally, orderBy
and related methods call appropriate array sorting functions (uasort
, krsort
, multisort
, usort
etc.).
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
add a comment |
up vote
9
down vote
up vote
9
down vote
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.
$sortedByName = from($objects)->orderBy('$v->name');
$sortedByCount = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
Comparisons can be further customized by passing a callback as a second argument, for example:
$sortedByFilenameNat = from($objects)->orderBy('$v->filename', 'strnatcmp');
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.
Internally, orderBy
and related methods call appropriate array sorting functions (uasort
, krsort
, multisort
, usort
etc.).
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
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.
$sortedByName = from($objects)->orderBy('$v->name');
$sortedByCount = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
Comparisons can be further customized by passing a callback as a second argument, for example:
$sortedByFilenameNat = from($objects)->orderBy('$v->filename', 'strnatcmp');
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.
Internally, orderBy
and related methods call appropriate array sorting functions (uasort
, krsort
, multisort
, usort
etc.).
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
edited Sep 18 '16 at 12:49
answered Jun 4 '15 at 0:58
Athari
27.4k1081125
27.4k1081125
add a comment |
add a comment |
up vote
3
down vote
Multidimensional sort by key value
Natural sort of a multidimensional array by a key value and also keep the original order(do not shuffle the main keys):
function multisortByKeyValue( $k, $arr ) {
$ids = array();
$index = 1;
foreach ( $arr as $key => $row ) {
$ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
$index ++;
}
natsort( $ids );
$arr = array_merge( $ids, $arr );
return $arr;
}
Test case:
$arr = array(
'id1' => array(
'label' => 'ID 1',
'priority' => 30,
),
'id2' => array(
'label' => 'ID 2',
'priority' => 70,
),
'id3' => array(
'label' => 'ID 3',
'priority' => 20,
),
'id4' => array(
'label' => 'ID 4',
'priority' => 30,
),
);
$sorted = multisortByKeyValue( 'priority', $arr );
// $sorted equals to:
/*
array (
'id3' => array (
'label' => 'ID 3',
'priority' => 20,
),
'id1' => array (
'label' => 'ID 1',
'priority' => 30,
),
'id4' => array (
'label' => 'ID 4',
'priority' => 30,
),
'id2' => array (
'label' => 'ID 2',
'priority' => 70,
),
)
*/
add a comment |
up vote
3
down vote
Multidimensional sort by key value
Natural sort of a multidimensional array by a key value and also keep the original order(do not shuffle the main keys):
function multisortByKeyValue( $k, $arr ) {
$ids = array();
$index = 1;
foreach ( $arr as $key => $row ) {
$ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
$index ++;
}
natsort( $ids );
$arr = array_merge( $ids, $arr );
return $arr;
}
Test case:
$arr = array(
'id1' => array(
'label' => 'ID 1',
'priority' => 30,
),
'id2' => array(
'label' => 'ID 2',
'priority' => 70,
),
'id3' => array(
'label' => 'ID 3',
'priority' => 20,
),
'id4' => array(
'label' => 'ID 4',
'priority' => 30,
),
);
$sorted = multisortByKeyValue( 'priority', $arr );
// $sorted equals to:
/*
array (
'id3' => array (
'label' => 'ID 3',
'priority' => 20,
),
'id1' => array (
'label' => 'ID 1',
'priority' => 30,
),
'id4' => array (
'label' => 'ID 4',
'priority' => 30,
),
'id2' => array (
'label' => 'ID 2',
'priority' => 70,
),
)
*/
add a comment |
up vote
3
down vote
up vote
3
down vote
Multidimensional sort by key value
Natural sort of a multidimensional array by a key value and also keep the original order(do not shuffle the main keys):
function multisortByKeyValue( $k, $arr ) {
$ids = array();
$index = 1;
foreach ( $arr as $key => $row ) {
$ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
$index ++;
}
natsort( $ids );
$arr = array_merge( $ids, $arr );
return $arr;
}
Test case:
$arr = array(
'id1' => array(
'label' => 'ID 1',
'priority' => 30,
),
'id2' => array(
'label' => 'ID 2',
'priority' => 70,
),
'id3' => array(
'label' => 'ID 3',
'priority' => 20,
),
'id4' => array(
'label' => 'ID 4',
'priority' => 30,
),
);
$sorted = multisortByKeyValue( 'priority', $arr );
// $sorted equals to:
/*
array (
'id3' => array (
'label' => 'ID 3',
'priority' => 20,
),
'id1' => array (
'label' => 'ID 1',
'priority' => 30,
),
'id4' => array (
'label' => 'ID 4',
'priority' => 30,
),
'id2' => array (
'label' => 'ID 2',
'priority' => 70,
),
)
*/
Multidimensional sort by key value
Natural sort of a multidimensional array by a key value and also keep the original order(do not shuffle the main keys):
function multisortByKeyValue( $k, $arr ) {
$ids = array();
$index = 1;
foreach ( $arr as $key => $row ) {
$ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
$index ++;
}
natsort( $ids );
$arr = array_merge( $ids, $arr );
return $arr;
}
Test case:
$arr = array(
'id1' => array(
'label' => 'ID 1',
'priority' => 30,
),
'id2' => array(
'label' => 'ID 2',
'priority' => 70,
),
'id3' => array(
'label' => 'ID 3',
'priority' => 20,
),
'id4' => array(
'label' => 'ID 4',
'priority' => 30,
),
);
$sorted = multisortByKeyValue( 'priority', $arr );
// $sorted equals to:
/*
array (
'id3' => array (
'label' => 'ID 3',
'priority' => 20,
),
'id1' => array (
'label' => 'ID 1',
'priority' => 30,
),
'id4' => array (
'label' => 'ID 4',
'priority' => 30,
),
'id2' => array (
'label' => 'ID 2',
'priority' => 70,
),
)
*/
answered Jan 30 at 19:26
Andrei Surdu
1,63721528
1,63721528
add a comment |
add a comment |
up vote
2
down vote
It is very convenient to sort arrays with sorted function from Nspl:
Basic sorting
// Sort array
$sorted = sorted([3, 1, 2]);
// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);
Sorting by function result
// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');
// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; });
// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));
// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0
Sorting multidimensional array
// Sort multidimensional array (sort list of users by their names)
$users = [
array('name' => 'Robert', 'age' => 20),
array('name' => 'Alex', 'age' => 30),
array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));
// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key
Sorting array of objects
// 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
Sorting with a comparison function
// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');
// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
return chr($v1[0]) - chr($v2[0]);
});
You can see all these examples here.
add a comment |
up vote
2
down vote
It is very convenient to sort arrays with sorted function from Nspl:
Basic sorting
// Sort array
$sorted = sorted([3, 1, 2]);
// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);
Sorting by function result
// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');
// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; });
// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));
// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0
Sorting multidimensional array
// Sort multidimensional array (sort list of users by their names)
$users = [
array('name' => 'Robert', 'age' => 20),
array('name' => 'Alex', 'age' => 30),
array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));
// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key
Sorting array of objects
// 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
Sorting with a comparison function
// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');
// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
return chr($v1[0]) - chr($v2[0]);
});
You can see all these examples here.
add a comment |
up vote
2
down vote
up vote
2
down vote
It is very convenient to sort arrays with sorted function from Nspl:
Basic sorting
// Sort array
$sorted = sorted([3, 1, 2]);
// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);
Sorting by function result
// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');
// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; });
// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));
// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0
Sorting multidimensional array
// Sort multidimensional array (sort list of users by their names)
$users = [
array('name' => 'Robert', 'age' => 20),
array('name' => 'Alex', 'age' => 30),
array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));
// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key
Sorting array of objects
// 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
Sorting with a comparison function
// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');
// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
return chr($v1[0]) - chr($v2[0]);
});
You can see all these examples here.
It is very convenient to sort arrays with sorted function from Nspl:
Basic sorting
// Sort array
$sorted = sorted([3, 1, 2]);
// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);
Sorting by function result
// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');
// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; });
// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));
// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0
Sorting multidimensional array
// Sort multidimensional array (sort list of users by their names)
$users = [
array('name' => 'Robert', 'age' => 20),
array('name' => 'Alex', 'age' => 30),
array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));
// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key
Sorting array of objects
// 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
Sorting with a comparison function
// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');
// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
return chr($v1[0]) - chr($v2[0]);
});
You can see all these examples here.
edited Jan 15 '16 at 23:29
answered Jan 15 '16 at 23:03
Ihor Burlachenko
2,0871417
2,0871417
add a comment |
add a comment |
up vote
0
down vote
There are several ways to sort an array.I will mention some methods for doing that task.fist of all , I will give an integer array which is called as '$numbers'.
$number = array(8,9,3,4,0,1,2);
This is the normal way to creating an array. Suppose that , I want to sort that array in ascending order.For that, 'sort()' method can be used.
<?php
$number = array(8,9,3,4,0,1,2);
sort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output of that,
You can see printed number array is sorted. If you want to that number array to be sort is descending order, 'rsort()' method can be use for that task.
<?php
$number = array(8,9,3,4,0,1,2);
rsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
consider the output..
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,
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
So ,Now I want to sort this array in ascending order according their value.'asort()' method can be used for that.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
asort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
If sorting descending order according their value,'arsort()' method can be used.
Suppose that you want to sort that array according their key value. In this , 'ksort()' method can be use.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
ksort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output.
Now array is sorted according their key value.If You want to sort the array in descending order according their key value,'krsort()' method can be used.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
krsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now associative array is sorted in descending order according their key value.Look at the output.
These are the some methods for sorting an array in ascending or descending order in php.I hope to you could get an idea.Thank you!
add a comment |
up vote
0
down vote
There are several ways to sort an array.I will mention some methods for doing that task.fist of all , I will give an integer array which is called as '$numbers'.
$number = array(8,9,3,4,0,1,2);
This is the normal way to creating an array. Suppose that , I want to sort that array in ascending order.For that, 'sort()' method can be used.
<?php
$number = array(8,9,3,4,0,1,2);
sort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output of that,
You can see printed number array is sorted. If you want to that number array to be sort is descending order, 'rsort()' method can be use for that task.
<?php
$number = array(8,9,3,4,0,1,2);
rsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
consider the output..
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,
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
So ,Now I want to sort this array in ascending order according their value.'asort()' method can be used for that.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
asort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
If sorting descending order according their value,'arsort()' method can be used.
Suppose that you want to sort that array according their key value. In this , 'ksort()' method can be use.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
ksort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output.
Now array is sorted according their key value.If You want to sort the array in descending order according their key value,'krsort()' method can be used.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
krsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now associative array is sorted in descending order according their key value.Look at the output.
These are the some methods for sorting an array in ascending or descending order in php.I hope to you could get an idea.Thank you!
add a comment |
up vote
0
down vote
up vote
0
down vote
There are several ways to sort an array.I will mention some methods for doing that task.fist of all , I will give an integer array which is called as '$numbers'.
$number = array(8,9,3,4,0,1,2);
This is the normal way to creating an array. Suppose that , I want to sort that array in ascending order.For that, 'sort()' method can be used.
<?php
$number = array(8,9,3,4,0,1,2);
sort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output of that,
You can see printed number array is sorted. If you want to that number array to be sort is descending order, 'rsort()' method can be use for that task.
<?php
$number = array(8,9,3,4,0,1,2);
rsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
consider the output..
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,
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
So ,Now I want to sort this array in ascending order according their value.'asort()' method can be used for that.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
asort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
If sorting descending order according their value,'arsort()' method can be used.
Suppose that you want to sort that array according their key value. In this , 'ksort()' method can be use.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
ksort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output.
Now array is sorted according their key value.If You want to sort the array in descending order according their key value,'krsort()' method can be used.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
krsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now associative array is sorted in descending order according their key value.Look at the output.
These are the some methods for sorting an array in ascending or descending order in php.I hope to you could get an idea.Thank you!
There are several ways to sort an array.I will mention some methods for doing that task.fist of all , I will give an integer array which is called as '$numbers'.
$number = array(8,9,3,4,0,1,2);
This is the normal way to creating an array. Suppose that , I want to sort that array in ascending order.For that, 'sort()' method can be used.
<?php
$number = array(8,9,3,4,0,1,2);
sort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output of that,
You can see printed number array is sorted. If you want to that number array to be sort is descending order, 'rsort()' method can be use for that task.
<?php
$number = array(8,9,3,4,0,1,2);
rsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
consider the output..
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,
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
So ,Now I want to sort this array in ascending order according their value.'asort()' method can be used for that.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
asort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
If sorting descending order according their value,'arsort()' method can be used.
Suppose that you want to sort that array according their key value. In this , 'ksort()' method can be use.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
ksort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now consider the output.
Now array is sorted according their key value.If You want to sort the array in descending order according their key value,'krsort()' method can be used.
<?php
$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
krsort($number);
foreach ($number as $value) {
echo $value." ";
}
?>
Now associative array is sorted in descending order according their key value.Look at the output.
These are the some methods for sorting an array in ascending or descending order in php.I hope to you could get an idea.Thank you!
answered Aug 26 at 14:14
GT_hash
515
515
add a comment |
add a comment |
up vote
-1
down vote
The simplest is to use usort function to sort array without any looping :
Below is an example :
$array_compare= array("0" =>4,"1"=>2,"2"=>500,"3"=>100);
This will sort in desending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) > 0 ? 1 :-1;
});
This will sort in asending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) < 0 ? 1 :-1;
});
1
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
add a comment |
up vote
-1
down vote
The simplest is to use usort function to sort array without any looping :
Below is an example :
$array_compare= array("0" =>4,"1"=>2,"2"=>500,"3"=>100);
This will sort in desending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) > 0 ? 1 :-1;
});
This will sort in asending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) < 0 ? 1 :-1;
});
1
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
add a comment |
up vote
-1
down vote
up vote
-1
down vote
The simplest is to use usort function to sort array without any looping :
Below is an example :
$array_compare= array("0" =>4,"1"=>2,"2"=>500,"3"=>100);
This will sort in desending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) > 0 ? 1 :-1;
});
This will sort in asending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) < 0 ? 1 :-1;
});
The simplest is to use usort function to sort array without any looping :
Below is an example :
$array_compare= array("0" =>4,"1"=>2,"2"=>500,"3"=>100);
This will sort in desending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) > 0 ? 1 :-1;
});
This will sort in asending order :
usort($array_compare, function($a, $b) {
return ($b['x1'] - $a['x1']) < 0 ? 1 :-1;
});
answered May 25 '16 at 7:34
pihu
728
728
1
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
add a comment |
1
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
1
1
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
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
add a comment |
protected by deceze♦ Oct 28 '14 at 6:11
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).
Would you like to answer one of these unanswered questions instead?
1
Problem: 99% of the unique snowflake questions (ha) are one-offs with absolutely no pre-question research :|
– jterry
Jun 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 Jardim
Jun 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.
– hakre
Jun 28 '13 at 12:04
1
@deceze: If nobody RTFM, nobody will also RTFQA - the existing Q&A :)
– hakre
Jun 28 '13 at 12:09