views:

36

answers:

4

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

  1. reallylongname
  2. mediumname
  3. shortname

mediumname shortname

Many thanks

+1  A: 

Take a look on uksort.

a1ex07
+5  A: 

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".

thetaiko
+1  A: 

Based on @thetaiko answer, with a simpler callback :

function sortByLengthReverse($a, $b){
    return strlen($b) - strlen($a);
}

uksort($nametocode, "sortByLengthReverse");

Resources :

Colin Hebert
A: 

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.

Gumbo
@Gumbo - out of curiosity, is there a performance advantage to this over `uksort()`?
thetaiko
@thetaiko: No, I don’t think so. But you’ll have to profile to be sure. The main difference is that there is no custom comparison function required as the key values are compared to distinguish the order.
Gumbo