Re: Sort by string length...
| From: | tg-php at gryffyndevelopment dot com | Date: | Wed, 22 Dec 2004 00:46:30 +0000 |
| Subject: | Re: Sort by string length... | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-204914@lists.php.net to get a copy of this message | ||
Is it an associative array? That is, are you assigning values like this:
Method 1:
$arr[] = "some text string";
or
$arr = array("some text string","some text string too");
or like this...
Method 2:
$arr["value1"] = "some text string";
or
$arr1 = array("value1"=>"some text string","value2"=>"some
text string too");
If you do it the first way, Method 1 (non-associative) then you could do this:
<?php
$arr1 = array("some text string","some text string too");
foreach ($arr1 as $value) {
$length = strlen($value);
$tmparr[$length][] = $value;
}
sort($tmparr);
reset($tmparr);
foreach ($tmparr as $lenarr) {
foreach ($lenarr as $value) {
$arr2[] = $value;
}
}
?>
Now $arr2 has a string length sorted list of your values.. or something close to it. I may have a
little syntax off a bit, but you get the idea.
I don't know of any way to actually just sort by string length, you'll have your make your
own function like the one above. Just remember that if you use $tmparr[$length] that you may have
multiple strings of the same length which will overwrite each other if you don't do another
layer like I did (with $tmparr[$length][] = $value);
Just gotta get a little clever with it.
Good luck!
-TG
= = = Original message = = =
Any idea how to sort an array by string length?
Russ Jones
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
___________________________________________________________
Sent by ePrompter, the premier email notification software.
Free download at http://www.ePrompter.com.