Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array of string by length and maintain their keys in PHP?

There is an array of strings;

$arr=array('longstring','string','thelongeststring');

so the keys are:

0=>'longstring'
1=>'string'
2=>'thelongeststring'

I want to sort it by length of strings, from longest to shortest, but without changing their keys;

$arrSorted=array(**2**=>'thelongeststring', **0**=>'longstring', **1**=>'string');

I am working with PHP since 2 days so that is what I already know that could be helpful with this case:

...
    usort($twoDim, 'sorting');
}

function sorting($a, $b) {
    return strlen($b) - strlen($a);
}

That is giving me array with string sorted by length, but with new keys. Another thing is asort which sorts an array alphabetical and maintain its keys. But I have no idea how to do these two things in the same time...

Please help!

like image 268
Sheb Avatar asked Jan 30 '23 11:01

Sheb


1 Answers

Use uasort:

uasort — Sort an array with a user-defined comparison function and maintain index association

usort doesn't maintain index associations.

Use it like this:

function sortByLength ($a, $b) {
    return strlen($b) - strlen($a);
}

$arr = ['longstring', 'string', 'thelongeststring'];

uasort($arr, 'sortByLength');

print_r($arr);

eval.in demo

This returns:

Array
(
    [2] => thelongeststring
    [0] => longstring
    [1] => string
)
like image 185
Ethan Avatar answered Feb 02 '23 08:02

Ethan