How to sort an array by string length and then by value in PHP?

I am currently sorting an array by the length of a string. But, when the string lengths are equal, how do I sort by value?

As an example, my current code is:

$array = array("A","BC","AA","C","BB", "B"); function lensort($a,$b){ return strlen($a)-strlen($b); } usort($array,'lensort'); print_r($array); 

Outputs:

 Array ( [0] => C [1] => A [2] => B [3] => BB [4] => AA [5] => BC ) 

But I would like it to be sorted as follows:

 Array ( [0] => A [1] => B [2] => C [3] => AA [4] => BB [5] => BC ) 
+8
sorting arrays php
source share
1 answer

Include both checks in the comparator:

 function lensort($a,$b){ $la = strlen( $a); $lb = strlen( $b); if( $la == $lb) { return strcmp( $a, $b); } return $la - $lb; } 

You can see from this demo that will be printed:

 Array ( [0] => A [1] => B [2] => C [3] => AA [4] => BB [5] => BC ) 
+11
source share

All Articles