solitario
Dec 12th, 2006, 02:54 PM
Hello all.
Could anyone tell me how to sort the elements of an array according the the length of each element, in descending order?
$search_string='Hello this the content of a querystring.';
$keywords=split(' ',$search_string);
So that the result would go something like:
querystring.
content
hello
this
the
of
a
usort() perhaps?
Much appreciated.
kows
Dec 12th, 2006, 04:41 PM
I would use explode() instead of split().
but anyway, I can't go to PHP.net right now for whatever reason, but I did come up with the following. If the keys of the array matter to you, then this probably wouldn't work THAT well for you, but the original keys are still preserved so it's entirely possible for you to get them if you need them. To combat the problem of different lengths replacing a key that already existed, I appended its original key via a decimal point, so each key is basically a unique decimal now. There might be other ways (and most likely better, too, I suppose) to do this, but I just came up with this one. I've also included the ability for you to either sort in ascending or descending order. For ascending, set the second parameter of strlen_sort to true (or leave it empty, it defaults to true), and for descending set it to false.
<pre>
<?php
$str = "This is a sentence with a few different variations of word length";
$arr = explode(" ", $str);
print_r($arr);
echo "\n\n";
print_r(strlen_sort($arr, true));
//FUNCTION strlen_sort(array arr[, boolean ascending = true])
//sort an array by string lengths, ascending or descending
//will return false if the passed value 'arr' is not an array
function strlen_sort($arr, $ascending = true){
if(!is_array($arr)) return false;
$narr = array();
for($i = 0; $i < count($arr); $i++)
$narr[strlen($arr[$i]) . '.' . $i] = $arr[$i];
$function = ($ascending) ? 'ksort' : 'krsort';
$function($narr);
return $narr;
}
?>
</pre>
The above will output:
Array
(
[0] => This
[1] => is
[2] => a
[3] => sentence
[4] => with
[5] => a
[6] => few
[7] => different
[8] => variations
[9] => of
[10] => word
[11] => length
)
Array
(
[10.8] => variations
[9.7] => different
[8.3] => sentence
[6.11] => length
[4.4] => with
[4.10] => word
[4.0] => This
[3.6] => few
[2.9] => of
[2.1] => is
[1.5] => a
[1.2] => a
)
If you want to print out the new array but were planning on using a for() loop, you can use a foreach() loop instead, like so:
<pre><?php
foreach(strlen_sort($arr) as $value){
echo $value . "\n";
}
//and if you need the keys too:
foreach(strlen_sort($arr) as $key => $value){
echo $key . ' => ' . $value . "\n";
}
?></pre>
Hope that helps.