4

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!

0

2 Answers 2

4

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

Good tip to keep in mind too, is that each sort function in the docs links to the same sorting comparison page, which makes it easy to figure out which method you need to use for your given problem: be2.php.net/manual/en/array.sorting.php
4

...how to do these two things in the same time

You're almost there.

usort + asort = uasort.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.