Lesson 50 of 100
Arrays15 min5 checksPHP 8.5

Sort Associative Arrays While Keeping Keys

Learn how asort(), arsort() and ksort() reorder PHP arrays in place without breaking key-value pairs, and how stable ordering resolves ties.

01 · THE IDEAREAD → TRY → LEARN

Why key association matters

An associative array stores pairs such as a player name and a score. If you only reorder the scores, the names no longer line up with them and the data is wrong. PHP therefore has sort functions that move whole pairs and keep each key attached to its value.

The plain sort() function does not do this. It reorders the values and then assigns new numeric keys, so your string keys are lost. For associative data, reach for one of these instead:

  • asort($array) sorts by value, ascending, and keeps keys.
  • arsort($array) sorts by value, descending, and keeps keys.
  • ksort($array) sorts by key, ascending.
  • krsort($array) sorts by key, descending.

All of them sort the variable in place. They take the array by reference, change it, and return true. Since PHP 8.2 the declared return type of asort() is true. Do not write $sorted = asort($data); expecting a new array, because you would just get true. Call the function, then keep using the original variable.

A first look

The example below sorts fruit names by their value. Notice that each letter key still points at the same fruit afterwards.

Example
<?php
$fruits = ["d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"];
asort($fruits);
echo json_encode($fruits, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
{"c":"apple","b":"banana","d":"lemon","a":"orange"}

The values come out alphabetically, and c still means apple.

Ascending and descending

Use arsort() when the biggest value should come first, such as a leaderboard or stock levels. Use ksort() when you want to order by the key instead.

Example
<?php
$stock = ["pear" => 4, "fig" => 9, "kiwi" => 4];
arsort($stock);
echo json_encode($stock, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
ksort($stock);
echo json_encode($stock, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
{"fig":9,"pear":4,"kiwi":4}
{"fig":9,"kiwi":4,"pear":4}

Look at pear and kiwi. Both have the value 4. After arsort(), pear stays ahead of kiwi because that was their original relative order.

Ties are stable

The manual notes that if two members compare as equal, they retain their original order. This has been guaranteed since PHP 8.0; before that, the order of equal elements was undefined. You can use this guarantee to build a two-level sort without writing a comparison callback: sort by the secondary rule first, then by the primary rule.

For a leaderboard that ranks by score descending and breaks ties alphabetically by name, first call ksort() so names are alphabetical, then arsort() so scores are descending. Equal scores keep their alphabetical order from the first step.

Example
<?php
$scores = ["zed" => 90, "amy" => 90, "max" => 85, "bo" => 100];
ksort($scores);
arsort($scores);
echo json_encode($scores, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
{"bo":100,"amy":90,"zed":90,"max":85}

Here bo leads with 100, and amy comes before zed because both have 90 and amy sorts first by name.

Sorting flags

Each function accepts an optional second argument, flags, which defaults to SORT_REGULAR. Other values include SORT_NUMERIC, SORT_STRING, SORT_NATURAL, and SORT_FLAG_CASE, which you combine with SORT_STRING or SORT_NATURAL for case-insensitive comparison. Pick a flag explicitly when your values are mixed or come from user input, because regular comparison follows PHP's usual comparison rules and can surprise you with numeric-looking strings.

Common mistakes

  1. Using sort() on associative data. The keys disappear.
  2. Using the return value. These functions return true, not the sorted array.
  3. Forgetting that the original is changed. Copy the array first if you still need the old order.
  4. Sorting in the wrong order for ties. Apply the secondary rule first, then the primary rule.
  5. Mixing key types. Keys that look like integers become integer keys, which affects comparison. Prefer clearly non-numeric keys in tests.

Your exercise

Write rankPlayers(array $scores): array. The input maps player names to numeric scores. Return a list of the names only, ordered by score from highest to lowest. Players with equal scores must appear in ascending alphabetical order by name. An empty input returns an empty list. The function must not depend on the order in which the input arrived. Think about which sort should run first, and remember that the sorts work on a local copy of the parameter, so the caller's array is not affected.

Before you start

Functions · Arrays · Types

You’ll practice
  • Sort keys or values while retaining associations
  • Implement and test a deterministic PHP 8.4 function
Your task

Make rankPlayers() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.