Search code examples
phparrayssortingassociative-array

Sort keys of an associative array in a specific order


I have an array that comes in this way since it's generated this way, and it's a heck of a task to change the way it's generated. This is part of it, there loads more.

$name['Age'] = '25';
$name['Location'] = 'Seattle';
$name['Last'] = 'Gates';
$name['First'] = 'Bill';

print_r($name);

How can I change it's order to something like below once it's generated?

$name['First'] = 'Bill';
$name['Last'] = 'Gates';
$name['Age'] = '25';
$name['Location'] = 'Seattle';

print_r($name);

Solution

  • Yes, there's a function that lets you reorder the associative array by keys according to your own criteria. It's called uksort:

    $key_order = array_flip(['First', 'Last', 'Age', 'Location']);
    uksort($name, function($key1, $key2) {
      return $key_order[$key1] - $key_order[$key2];
    });
    
    print_r($name);
    

    Demo.


    Having said all that, I can't help wondering ain't you need something different instead: changing the order of output of your array only. For example:

    $output_order = ['First', 'Last', 'Age', 'Location'];
    foreach ($output_order as $key) {
      echo $key, ' => ', $name[$key], PHP_EOL;
    }