Re: Sort by string length...
| From: | David Otton | Date: | Wed, 22 Dec 2004 01:03:35 +0000 |
| Subject: | Re: Sort by string length... | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-204915@lists.php.net to get a copy of this message | ||
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()).