How to Have a Stable Sort in PHP with Arsort()

How to have a stable sort in PHP with arsort()?

Construct a new array whose elements are the original array's keys, values, and also position:

$temp = array();
$i = 0;
foreach ($array as $key => $value) {
$temp[] = array($i, $key, $value);
$i++;
}

Then sort using a user-defined order that takes the original position into account:

uasort($temp, function($a, $b) {
return $a[2] == $b[2] ? ($a[0] - $b[0]) : ($a[2] < $b[2] ? 1 : -1);
});

Finally, convert it back to the original associative array:

$array = array();
foreach ($temp as $val) {
$array[$val[1]] = $val[2];
}

arsort() not stable

You don't need to sort the array if you're only looking for the preferred language:

<?php

function findPrefferedLanguage($languages) {
foreach ($languages as $lang => $weight) {
if (empty($key) || ($weight > $languages[$key])) {
$key = $lang;
}
}

return $key;
}

$foo = array('es' => .6, 'en' => 1, 'fr' => 1, 'de' => .5);

var_dump(findPrefferedLanguage($foo)); // en

Hastily tested... there's probably some edge-cases that will generate errors/warnings.

Preserve key order (stable sort) when sorting with PHP's uasort

Since PHP does not support stable sort after PHP 4.1.0, you need to write your own function.

This seems to do what you're asking: http://www.php.net/manual/en/function.usort.php#38827

As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal.

Sometimes you really do need a stable sort. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field. In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below. It is a merge sort, which is guaranteed O(n*log(n)) complexity, which means it stays reasonably fast even when you use larger lists (unlike bubblesort and insertion sort, which are O(n^2)).

<?php
function mergesort(&$array, $cmp_function = 'strcmp') {
// Arrays of size < 2 require no action.
if (count($array) < 2) return;
// Split the array in half
$halfway = count($array) / 2;
$array1 = array_slice($array, 0, $halfway);
$array2 = array_slice($array, $halfway);
// Recurse to sort the two halves
mergesort($array1, $cmp_function);
mergesort($array2, $cmp_function);
// If all of $array1 is <= all of $array2, just append them.
if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
$array = array_merge($array1, $array2);
return;
}
// Merge the two sorted arrays into a single sorted array
$array = array();
$ptr1 = $ptr2 = 0;
while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
$array[] = $array1[$ptr1++];
}
else {
$array[] = $array2[$ptr2++];
}
}
// Merge the remainder
while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
return;
}
?>

Also, you may find this forum thread interesting.

PHP combining arsort & ksort

PHP dropped stable sorting (which guaranteed the ordering you wanted) in PHP 4.1:
https://bugs.php.net/bug.php?id=53341&edit=1

Here's a seemingly dupe question, with a code snippet, to work around it (basically: write your own sort function. Boo.):
Preserve key order (stable sort) when sorting with PHP's uasort

Is Eloquent sortBy stable in Laravel 5?

The source code can be found in Illuminate/Support/Collection.php:

public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
{
$results = [];
if ( ! $this->useAsCallable($callback))
{
$callback = $this->valueRetriever($callback);
}
// First we will loop through the items and get the comparator from a callback
// function which we were given. Then, we will sort the returned values and
// and grab the corresponding values for the sorted keys from this array.
foreach ($this->items as $key => $value)
{
$results[$key] = $callback($value, $key);
}
$descending ? arsort($results, $options)
: asort($results, $options);
// Once we have sorted all of the keys in the array, we will loop through them
// and grab the corresponding model so we can set the underlying items list
// to the sorted version. Then we'll just return the collection instance.
foreach (array_keys($results) as $key)
{
$results[$key] = $this->items[$key];
}
$this->items = $results;
return $this;
}

Since the sort() family isn't stable, this function won't be stable either.

There are stable PHP sort functions, but if you want to use them you'll need to patch Laravel.

How can I sort arrays and data in PHP?

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);

You can also sort on more than one column each in either direction:

array_multisort(array_column($array, 'foo'), SORT_DESC,
array_column($array, 'bar'), SORT_ASC,
$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.

Sort a flat, associative array by numeric values, then by non-numeric keys

Have a look at examples #3:
http://php.net/manual/en/function.array-multisort.php

You'll need to create two arrays to use as indexes; one made up of the original array's keys and the other of the original array's values.

Then use multisort to sort by text values (keys of the original array) and then by the numeric values (values of the original array).



Related Topics



Leave a reply



Submit