PHP: Sort an array by the length of its values?

Use http://us2.php.net/manual/en/function.usort.php

with this custom function

function sort($a,$b){
    return strlen($b)-strlen($a);
}

usort($array,'sort');

Use uasort if you want to keep the old indexes, use usort if you don't care.

Also, I believe that my version is better because usort is an unstable sort.

$array = array("bbbbb", "dog", "cat", "aaa", "aaaa");
// mine
[0] => bbbbb
[1] => aaaa
[2] => aaa
[3] => cat
[4] => dog

// others
[0] => bbbbb
[1] => aaaa
[2] => dog
[3] => aaa
[4] => cat

If you'd like to do it the PHP 5.3 way, you might want to create something like this:

usort($array, function($a, $b) {
    return strlen($b) - strlen($a);
});

This way you won't pollute your global namespace.

But do this only if you need it at a single place in your source code to keep things DRY.


function sortByLength($a,$b){
  if($a == $b) return 0;
  return (strlen($a) > strlen($b) ? -1 : 1);
}
usort($array,'sortByLength');

PHP7 is coming. In PHP7, you could use the Spaceship Operator.

usort($array, function($a, $b) {
    return strlen($b) <=> strlen($a);
});

Hope this could help you in the future.

Tags:

Php

Arrays