Forum Moderators: coopster

Message Too Old, No Replies

sort array by string length

uasort?

         

brotherhood of LAN

12:35 am on Nov 24, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I've been muddling through functions to make a small search engine. I'm at the point where I have each word and its position in an array, the word position being the key and the word as the value.

Each word gets hashed to an integer value, and it's useful for me to have the values in the array ordered by their string length (in ascending order) to do this.

After a gander through the array functions in the PHP manual the closest match I see to this is uasort(array,function cmp_function)

Would this be the right function to use? And if it is, any idea what the function would look like to get them in ascending order of length...

brotherhood of LAN

1:12 am on Nov 24, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



ok forget i asked, slightly borrowed from perl.about.com/library/weekly/aa082203a.htm

$allwords = array("whatever","goes","in","here");
function Ascii_Sort($val_1, $val_2)
{
// initialize the return value to zero
$retVal = 0;

// compare lengths
$firstVal = strlen($val_1);
$secondVal = strlen($val_2);

if($firstVal > $secondVal)
{
$retVal = 1;
}
else if($firstVal < $secondVal)
{
$retVal = -1;
}
return $retVal;
}

uasort($allwords, "Ascii_Sort");
foreach($allwords as $val)
{
print "$val <BR>";
}

httpwebwitch

2:00 am on Dec 10, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



thanks for posting that anyways, I was looking for a way to do the same thing. Cheers!