• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 934
  • Last Modified:

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.
  • 2
1 Solution
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.
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:
Brilliant!  Thank you.

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now