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!
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
)
                        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