PHP Sorting an array by the length of its values?

I created an anagram and I have an array of positive matches. The problem is that they are all in a different order, I want to be able to sort the array so that the longest values โ€‹โ€‹of the array are displayed first.

Anyone have any ideas on how to do this?

+45
arrays php
May 08 '09 at 4:22
source share
8 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 old indexes, use usort if you don't care.

Also, I think 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 
+124
May 08 '09 at 4:28
source share

If you want to do this with PHP 5.3, you may need to create something like this:

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

This way you will not pollute the global namespace.

But do this only if you need to be in one place in the source code to save DRY stuff.

+49
Dec 19 '11 at 12:51 on
source share

PHP7 is coming up. In PHP7 you can use the Spaceship Operator .

 usort($array, function($a, $b) { return strlen($b) <=> strlen($a); }); 

Hope this helps you in the future.

+16
Nov 23 '15 at 9:39
source share
 function sortByLength($a,$b){ if($a == $b) return 0; return (strlen($a) > strlen($b) ? -1 : 1); } usort($array,'sortByLength'); 
+9
May 08 '09 at 4:26
source share

Create an array of strlen elements of the oyur and multisort with your array.

 foreach($Yourarray as $c=>$key) { $key['maxlen'] = strlen($key); $sort_numcie[] = $key['maxlen']; } array_multisort($sort_numcie, $Yourarray); 

This will definitely work. I'm sure!

+1
Mar 05 '12 at 11:20
source share

In addition to the accepted answer for sorting an array by length with increasing or decreasing order :

 function strlen_compare($a,$b){ if(function_exists('mb_strlen')){ return mb_strlen($b) - mb_strlen($a); } else{ return strlen($b) - strlen($a); } } function strlen_array_sort($array,$order='dsc'){ usort($array,'strlen_compare'); if($order=='asc'){ $array=array_reverse($array); } return $array; } 
0
Sep 17 '14 at 12:05
source share

Here's how I did it in the past.

 // Here the sorting... $array = array_combine($words, array_map('strlen', $words)); arsort($array); 
-one
Sep 16 '09 at 10:12
source share

It's simple.

 function LSort(a,b){return a.length-b.length;} var YourArray=[[1,2,3,4,5,6], ['a','b'], ['X','Y','Z'], ['I','Love','You'], ['good man']]; YourArray.sort(Lsort); 

Result:

 ['good man'] Length=1 ['a','b'] Length=3 ['X','Y','Z'] Length=3 ['I','Love','You'] Length=3 [1,2,3,4,5,6] Length=6 
-5
Nov 06 2018-11-11T17
source share



All Articles