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?
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.
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.
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 />"; } ?>
The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With