PHP Sorting Arrays
Sorting changes order and sometimes changes keys. Choose the operation from whether those keys are positions or identifiers.
How it works
sort reindexes a list of values, asort preserves the key/value association, and ksort orders by keys. Comparator-based sorting needs a consistent negative/zero/positive result. If a report needs a tie-breaker, include one explicitly so its intended order is reviewable. Sorting an input in place is a mutation, so copy it first when another caller still needs the original order.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l array-sorting.php
php array-sorting.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
$stock = ["Saw"=>2,"Spade"=>5,"Drill"=>2];
ksort($stock);
foreach ($stock as $name=>$count) echo "$name: $count\n";
$rows = [["id"=>3,"count"=>2],["id"=>1,"count"=>2]];
usort($rows, fn(array $a,array $b): int => ($a["count"] <=> $b["count"]) ?: ($a["id"] <=> $b["id"]));
echo "First id: ", $rows[0]["id"], "\n";
Expected result
Drill: 2
Saw: 2
Spade: 5
First id: 1Key sorting keeps each stock quantity attached to its name. The row comparator orders by count and then ID, which makes equal counts predictable by the stated rule. The sorted list has positional keys; the record’s id field still carries the stable business identity.
Check the official PHP manual for detailed version and API contracts.