[PHP] Sort an array by value and preserve its keys with uasort()

Created on November 30, 2026

uasort() sorts array values using a comparison callback while preserving their associated keys. This example sorts products by ascending price and keeps their product IDs.

<?php

$products = [
    'p101' => ['name' => 'notebook', 'price' => 250],
    'p102' => ['name' => 'eraser', 'price' => 100],
    'p103' => ['name' => 'pencil', 'price' => 150],
];

uasort($products, fn($a, $b) => $a['price'] <=> $b['price']);

foreach ($products as $id => $product) {
    echo $id . ' ' . $product['name'] . ' ' . $product['price'] . ' yen' . PHP_EOL;
}
p102 eraser 100 yen
p103 pencil 150 yen
p101 notebook 250 yen

<=> returns a negative number, zero, or a positive number according to the order of the two prices. The sort updates the original array. You can still access the notebook with $products['p101']. To sort and reindex the keys from zero, use usort.

Reference

PHP