← All writing

Sort equal values with a deliberate secondary key

PHP 8.3+Sources checked 2026-09-13

A product list sorts by stock level. Many products share the same stock, so a stable secondary key makes the order predictable across pages and repeated runs. The spaceship operator expresses a three-way comparison without nested conditionals.

Compare the business fields in order

<?php
$rows = [['sku'=>'B','stock'=>2], ['sku'=>'A','stock'=>2], ['sku'=>'C','stock'=>1]];
usort($rows, fn ($a, $b) => ($a['stock'] <=> $b['stock']) ?: strcmp($a['sku'], $b['sku']));
assert(array_column($rows, 'sku') === ['C', 'A', 'B']);

The stock comparison comes first. When it returns zero, the SKU comparison breaks the tie. Keep the comparator consistent: a value should not randomly compare differently on repeated calls. Avoid external API calls or mutable counters inside a sort callback.

Know which keys survive

usort reindexes the result. If the original keys matter, choose an appropriate key-preserving sort and test the output structure. Sorting a displayed list and sorting a map keyed by IDs are different operations.

For large database-backed lists, sort in the database with a matching pagination strategy instead of loading all rows into PHP. Add a unique final ordering column when ties in earlier columns remain possible.

Test equal primary values, equal labels, negative or zero values if accepted, and the intended direction. If labels need locale-aware ordering, a byte-oriented string comparison may not match user expectations. Choose a collation rule deliberately rather than treating alphabetical order as universal.

Reference

Official documentation. The examples here illustrate the stated boundary; adapt them to your application and test its failure paths.