Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Sort an array by the length of its values?

Tags:

arrays

php

I made an anagram machine and I have an array of positive matches. The trouble is they are all in a different order, I want to be able to sort the array so the longest array values appear first.

Anybody have any ideas on how to do this?

like image 507
Sam152 Avatar asked May 08 '09 04:05

Sam152


People also ask

How do you sort an array by length of an element?

To sort the array by its string length, we can use the Array. sort() method by passing compare function as an argument. If the compare function return value is a. length - b.

How do you sort an array by a specific value in PHP?

PHP - Sort Functions For Arraysrsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key. arsort() - sort associative arrays in descending order, according to the value.

How can I sort an array in PHP without sort method?

php function sortArray() { $inputArray = array(8, 2, 7, 4, 5); $outArray = array(); for($x=1; $x<=100; $x++) { if (in_array($x, $inputArray)) { array_push($outArray, $x); } } return $outArray; } $sortArray = sortArray(); foreach ($sortArray as $value) { echo $value . "<br />"; } ?>

What is Rsort PHP?

The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.


1 Answers

Use http://us2.php.net/manual/en/function.usort.php

with this custom function

function sort($a,$b){     return strlen($b)-strlen($a); }  usort($array,'sort'); 

Use uasort if you want to keep the old indexes, use usort if you don't care.

Also, I believe that my version is better because usort is an unstable sort.

$array = array("bbbbb", "dog", "cat", "aaa", "aaaa"); // mine [0] => bbbbb [1] => aaaa [2] => aaa [3] => cat [4] => dog  // others [0] => bbbbb [1] => aaaa [2] => dog [3] => aaa [4] => cat 
like image 195
Unknown Avatar answered Oct 02 '22 01:10

Unknown