Question: I am having MAJOR usort() issues! :( So basically I want to sort my array by their values. I would like the values to display in this order: Platinum, Gold, Silver, Bronze, Complete, None, Uncomplete. Now I can sort them well, but I would like to preserve their key (is that possible?). here is my code:

```
function compareMedals( $a, $b ) {
    $aMap = array(1 => 'Platinum', 2 => 'Gold', 3 => 'Silver', 4 => 'Bronze', 5 => 'Complete', 6 => 'None', 7 => 'Uncomplete');
    $aValues = array( 1, 2, 3, 4, 5, 6, 7);
    $a = str_ireplace($aMap, $aValues, $a);
    $b = str_ireplace($aMap, $aValues, $b);
    return $a - $b;
}
usort($list, 'compareMedals');

```

So is it possible to sort them WHILE preserving their keys? Thank You! :)

**EDIT**

Array:

```
$array = array("post1" => 'Platinum', "Post2" => "Bronze, "Post3" = > Gold)

```

Should output:

```
"Post1" => 'Platinum',
"Post3" => 'Gold',
"Post2" => 'Bronze'

```

Yet it is outputting this:

```
"0" => 'Platinum',
"1" => 'Gold',
"2" => 'Bronze'

```

Answer: 
`usort` did not preserve the key, if you want to preserve key after sort then you should use `asort`. Hope this help you.
Considering these assumptions:

1. Your input array may contain values that are not unique (`Gold` may be the value for multiple posts).
2. You *know* (and can list) all of the potential values which will be used to sort the input array. (there will be no "outliers")

You can simplify your custom sort function by passing your "mapping array" (aka lookup array) as an associative array which has "status" as the keys and "sorting value" as values. I use `array_flip()` below, but you can write out the 1-dimensional associative array if you wish.

When calling `uasort()` to call the custom sorting function and preserve the input array's keys, use `use()` to pass the lookup array inside the function scope.

From php7, you can use the "spaceship operator" (aka three-way-comparison operator) to cleverly perform the comparison.

Clean, Brief, and Efficient.

Code: ([Demo](https://3v4l.org/Cr86T))

```
$array = ["Post1" => "Platinum", "Post2" => "Bronze", "Post3" => "Gold", "Post4" => "Uncomplete", "Post5" => "Gold"];

$order = array_flip(["Platinum", "Gold", "Silver", "Bronze", "Complete", "None", "Uncomplete"]);
// makes: array ('Platinum' => 0, 'Gold' => 1, 'Silver' => 2, 'Bronze' => 3, 'Complete' => 4, 'None' => 5, 'Uncomplete' => 6)

uasort($array, function ($a, $b) use ($order) {
    return $order[$a] <=> $order[$b];
});

var_export($array);

```

Output:

```
array (
  'Post1' => 'Platinum',
  'Post3' => 'Gold',
  'Post5' => 'Gold',
  'Post2' => 'Bronze',
  'Post4' => 'Uncomplete',
)

```

---

From PHP7.4, you can use arrow syntax to omit the `use()` declaration and shorten the total syntax.

[PHP7.4+ Demo](https://3v4l.org/BJNaY)

```
uasort($array, fn($a, $b) => $order[$a] <=> $order[$b]);

```