Re: Sort by string length...

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, 21 Dec 2004 16:18:52 -0500 (EST), you wrote:

>Any idea how to sort an array by string length?

You write a function that compares two strings (A and B), and returns
0 if len(A) == len(B), -1 if len(A) < len(B) or +1 if len(A) > len(B).

function compare_by_length ($a, $b)
{
    $la = strlen ($a);
    $lb = strlen ($b);
    if ($la == $lb) return (0);
    return ($a < $b) ? -1 : 1;
}

Then, you pass the array to be sorted and the comparison function to
one of the  u*sort() functions:

usort ($array, 'compare_by_length');

(Caution: untested code. Also, consider what happens when you pass a
jagged array to usort()).

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux