1

I would like to have a unique sort function for several associative arrays.

The best candidate among the various PHP sort functions would be uksort(), (usort() would be ideal, but it changes the array keys to become the numerical index(!)).

For instance (using a simpler array)

  function sorting_by_length_desc ($a, $b) 
  {
    return strlen($GLOBALS['arr'][$b]) - strlen($GLOBALS['arr'][$a]);
  }

  $arr = ('chandler' => 'bing', 'monica' => 'lewinsky');

  uksort($arr, 'sorting_by_length_desc');

will make $arr to be

  ('monica' => 'lewinsky', 'chandler' => 'bing');

without affecting the keys.

So how to use the same sort function for any array, uksort() being called at various places in the code? For instance for $arr1, $arr2, ..., $arrn?
Is it necessary to use another global var with the array name to be assigned to the array to be sorted (before the sort), and used globally in the sort function?

There must be something else, cleaner, right?

2
  • 1
    Shouldn't it be 'monica' => 'geller' ? ;) Commented Oct 8, 2010 at 6:08
  • @codaddict You nailed it! Commented Dec 6, 2020 at 0:04

2 Answers 2

1

You can have a common comparison function like:

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

Also uksort sorts the array on keys. Is that what you are looking for?

If you want to sort the arrays on value maintaining the key,value association you can use uasort.

Sign up to request clarification or add additional context in comments.

1 Comment

I completely missed this func for some reason! uasort() is exactly what is needed to achieve the problem I had in the first place. Thanks.
0

You can achieve this by uksort() function

  $arr = array('chandler' => 'bing', 'monica' => 'lewinsky', 'name' => 'smallest one');

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

  $result = $arr;

Result(sorted as smallest string length of array keys):

Array
    (
        [name] => smallest one
        [monica] => lewinsky
        [chandler] => bing
    )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.