PHP Sort Associative Array Key Length

Howdy all,
  Does anyone have a good fast method for sorting an associative array by the key's string length?  Example:

$m['aa'] = true;
$m['abb'] = true;
$m['b'] = true;
$m['dddd'] = true;
$m['bb'] = true;
$m['c'] = true;

Will get sorted as:


See?  Sorting by the longest index/key to the shortest.  Also it's likely that the arrays will be multidimensional with associative arrays inside, so I need to maintaining key to data correlations all the way through.
Who is Participating?
You can use uksort to define your own sorting function:


$m['aa'] =  array('bb' => true, 'aa' => true);
$m['abb'] =  array('bb' => true, 'aa' => true);
$m['b'] =  array('bb' => true, 'aa' => true);
$m['dddd'] =  array('bb' => true, 'aa' => true);
$m['bb'] =  array('bb' => true, 'aa' => true);
$m['c'] =  array('bb' => true, 'aa' => true);

uksort($m, 'mySort');


function mySort($key1, $key2) {
  $s1 = strlen($key1);
  $s2 = strlen($key2);
  if($s1 == $s2) return 0;
  return $s1 > $s2 ? -1 : 1;


headzooAuthor Commented:
Just a quick clarification: Even though the associative array is multidimensional, the arrays "inside" shouldn't affect the sorting at all.  Example:

$m['aa'] = array('bb' => true, 'aa' => true);
$m['bbb'] = array('a' => true, 'b' => true);

Will get sorted as:

$m['bbb'] = array('a' => true, 'b' => true);
$m['aa'] = array('bb' => true, 'aa' => true);

Only the base key's need to be sorted.
headzooAuthor Commented:
Brilliant!  Thank you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.