Skip to content
Advertisement

PHP: Sort array by value length

I am trying to sort an array by the length of characters in each value (and perhaps, if possible, in alphabetical order if two values have the same length of characters). For example:

Array ( [0] => this [1] => is [2] => a [3] => bunch [4] => of [5] => words;

I am trying to sort this array to look like:

Array ( [0] => a [1] => is [2] => of [3] => this [4] => bunch [5] => words;

How?

Advertisement

Answer

This should do it:

array_multisort(array_map('strlen', $array), $array);
  • Get the length of each string in an array by mapping strlen() using array_map()
  • Sort on the string lengths and sort the original array by the string length sorted array using array_multisort()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement