PHP / CHAPTER 06

Sorting keys, records, and ties

Intermediate

Choose the sorting operation that preserves the required information.

By the end of this chapter

  • Distinguish sort from key-preserving sorts
  • Define compound record order
  • Avoid relying on incidental traversal order

The idea

PHP arrays are ordered maps, so sorting can change both traversal order and key handling. sort orders values and reindexes numeric keys, while asort preserves key associations as it orders values. A record list often needs usort with an explicit comparator. Choose the operation by deciding whether keys identify records or merely represent their current positions.

A comparator should return a negative value, zero, or a positive value according to the intended order. The spaceship operator expresses this comparison directly for suitable values. Add a secondary key when ties must be deterministic, such as score followed by identifier. Sorting changes the supplied array variable, so make an ordinary array copy first if the caller’s order must remain unchanged, while remembering that nested objects can still be shared.

PHP example
<?php
$rows=[["score"=>2,"id"=>"b"],["score"=>1,"id"=>"c"],["score"=>2,"id"=>"a"]];
usort($rows,fn($a,$b)=>($a["score"]<=>$b["score"]) ?: ($a["id"]<=>$b["id"]));
echo implode(",",array_column($rows,"id")),"\n";
Result
c,a,b

The primary comparison orders scores; only equal scores reach the identifier comparison.

Try it yourself

Sort a keyed score map by values while retaining each key’s association.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which operation orders values while retaining their associated keys?