We help IT Professionals succeed at work.

PHP Sort Associative Array Key Length

headzoo asked
Medium Priority
Last Modified: 2012-05-05
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.
Watch Question


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.
Top Expert 2006
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;



Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts


Brilliant!  Thank you.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.