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?
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?
function sortByLength($a,$b){
if($a == $b) return 0;
return (strlen($a) > strlen($b) ? -1 : 1);
}
usort($array,'sortByLength');
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
Here's a way I've done it in the past.
// Here's the sorting...
$array = array_combine($words, array_map('strlen', $words));
arsort($array);