Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 920
MultiDev Avatar asked Jul 21 '14 21:07

MultiDev


2 Answers

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()
like image 63
AbraCadaver Avatar answered Sep 21 '22 11:09

AbraCadaver


Looks like others have already answered but I started writing this so I'm going to post it, dang it! :)

You could take a look at usort

$data = ["this", "is", "a", "bunch", "of", "words"];

usort($data, function($a, $b) {
    $difference =  strlen($a) - strlen($b);

    return $difference ?: strcmp($a, $b);
});

I'm using the Elvis operator ?: to just return the difference based on the string lengths if it's not 0. If it is 0, just return the return value of strcmp

like image 42
jcbwlkr Avatar answered Sep 24 '22 11:09

jcbwlkr