tags:

views:

1552

answers:

3

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?

+7  A: 
function sortByLength($a,$b){
  if($a == $b) return 0;
  return (strlen($a) > strlen($b) ? -1 : 1);
}
usort($array,'sortByLength');
zalew
There's a bug in this. Your equality condition is too narrow. The strings "abc" and "def" should return 0 from this sort, but won't. They will instead return 1. And while I realize that this isn't a grave error (the output won't *look* broken, it's technically inaccurate.
Peter Bailey
'if($a == $b) return 0;' this is a mistake. We are talking about length.
Thinker
@ Peter and Thinker, yes its an oddity of the PHP manual. I myself did strlen($a) == strlen($b), but then I saw that since PHP uses an unstable sort, it doesn't matter! It still messes up the order. So I came up with the shortest function that works.
Unknown
So its pretty sad that the PHP manual promotes bad programming, but since their language is poorly designed, it doesn't cause an actual bug.
Unknown
Had it from some example based on the manual (as unknown said), didn't really bother to analyse that as I'm not into php lately, just checked if it works. Got sth better - good.
zalew
Yep, the manual examples and comments sometimes are very sad, but I don't know if it's really worth giving a damn :) Cheerz.
zalew
+12  A: 

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
Unknown
+1 ... please let this bubble up!
alex
This is good, though I wouldn't call the function just 'sort'. sortByLength below is more descriptive.
spilth
A: 

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);
Joe Beeson