JROB JROB - 6 months ago 105
PHP Question

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?

Answer

This should do it:

array_multisort(array_map('strlen', $array), $array);
  • Get the length of each string in an array using strlen() and array_map()
  • Sort on the string lengths and sort the original array by the string length sorted array using array_multisort()
Comments