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
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.
Take a look on uksort.
Based on @thetaiko answer, with a simpler callback :
Resources :
uksort()
strlen()
One limitation while sorting the keys on the basis of length is that: equal length keys are not re-ordered. Say we need to order the keys by length in
descending
order.Output will be:
Notice the order of
elephant
anddog
for example (or others) in two sorting methods. The second method looks better. There may be easier ways to solve this but hope this helps someone...Behold my powerful inline methodologies. Preserve global space for the generations to come!