I've found a few answers to sorting by value, but not key.
What I'd like to do is a reverse sort, so with:
$nametocode['reallylongname']='12';
$nametocode['shortname']='10';
$nametocode['mediumname']='11';
I'd like them to be in this order
mediumname shortname
Many thanks
Another solution using array_multisort
:
$keys = array_map('strlen', array_keys($arr));
array_multisort($keys, SORT_DESC, $arr);
Here $keys
is an array of the lengths of the keys of $arr
. That array is sorted in descending order and then used to sort the values of $arr
using array_multisort
.
I have benchmarked some of sorting algorithms since performance is important for my project - here's what I've found (averaged result ran 1000x, sorted field had cca 300 elements with key size 3-50 chars):
Sometime simple foreach still wins. Using dynamic PHP features has some performance penalty, obviously.
Based on @thetaiko answer, with a simpler callback :
function sortByLengthReverse($a, $b){
return strlen($b) - strlen($a);
}
uksort($nametocode, "sortByLengthReverse");
uksort()
strlen()
You can use a user defined key sort function as a callback for uksort
:
function cmp($a, $b)
{
if (strlen($a) == strlen($b))
return 0;
if (strlen($a) > strlen($b))
return 1;
return -1;
}
uksort($nametocode, "cmp");
foreach ($nametocode as $key => $value) {
echo "$key: $value\n";
}
Quick note - to reverse the sort simply switch "1" and "-1".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With