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

I made an anagram machine and I have an array of positive matches. The trouble is they are all in a different order, I want to be able to sort the array so the longest array values appear first.

Anybody have any ideas on how to do this?


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.


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.