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
- reallylongname
- mediumname
- shortname
mediumname shortname
Many thanks
The code below sorts the PHP hash array by string length of the key, then by the case-sensitive key itself, both in ascending order, using a lambda function:
This code does the same in reverse order:
Another solution using
array_multisort
: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
usingarray_multisort
.To absolutely use uksort you can do like this:
Output:
I have tested this code.
In PHP7+ you can use
uksort()
with spaceship operator and anonymous function like this:You can use a user defined key sort function as a callback for
uksort
:Quick note - to reverse the sort simply switch "1" and "-1".
A simple problem requires a simple solution ;-)