sort array by length and then alphabetically

Viewed 2237

I'm trying to make a way to sort words first by length, then alphabetically.

// from
$array = ["dog", "cat", "mouse", "elephant", "apple"];

// to
$array = ["cat", "dog", "apple", "mouse", "elephant"];

I've seen this answer, but it's in Java, and this answer, but it only deals with the sorting by length. I've tried sorting by length, using the code provided in the answer, and then sorting alphabetically, but then it sorts only alphabetically.

How can I sort it first by length, and then alphabetically?

3 Answers

This is not as short as other methods, but I would argue that it's clearer, and can be easily extended to cover other use cases:

$f = function ($s1, $s2) {
   $n = strlen($s1) <=> strlen($s2);
   if ($n != 0) {
      return $n;
   }
   return $s1 <=> $s2;
};
usort($array, $f);
Related