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?
This should do it:
array_multisort(array_map('strlen', $array), $array);
strlen()
using array_map()
array_multisort()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With