Question
How to Sort an Array of Associative Arrays by Column Value in PHP
Question
Given the following PHP array:
$inventory = array(
array("type" => "fruit", "price" => 3.50),
array("type" => "milk", "price" => 2.90),
array("type" => "pork", "price" => 5.43),
);
How can I sort the elements of $inventory by the price field so that the result becomes:
$inventory = array(
array("type" => "pork", "price" => 5.43),
array("type" => "fruit", "price" => 3.50),
array("type" => "milk", "price" => 2.90),
);
In other words, how do I sort an array of associative arrays by one column value in descending order in PHP?
Short Answer
By the end of this page, you will understand how to sort an array of associative arrays in PHP using a custom comparison function. You will learn the most common approach with usort(), how ascending and descending sorting work, how to sort by different keys, and which beginner mistakes to avoid.
Concept
In PHP, when you have an array where each item is itself an associative array, you often need to sort the outer array based on one value inside each inner array.
In this example, each item has:
- a
type - a
price
You do not want to sort by the whole inner array. You want to sort by one specific field: price.
This is a common problem in real programs because data is often structured like this:
- products with
name,price, andstock - users with
name,age, andemail - API results with
id,created_at, andstatus
The main PHP tool for this is usort().
usort() lets you sort an array using your own comparison logic. You give it:
- the array to sort
- a function that compares two items
That comparison function must return:
- a value less than
0if the first item should come before the second 0if they are equal- a value greater than
0if the first item should come after the second
This matters because PHP cannot automatically know which field inside each associative array should be used for sorting. Your comparison function tells PHP exactly what to compare.
Mental Model
Think of usort() like asking a helper to arrange a stack of product cards.
Each card contains multiple pieces of information:
- type
- price
If you just say, “Sort these cards,” the helper does not know what to use.
So you give a rule:
- compare the
priceon card A and card B - if A is more expensive, put A first
- if B is more expensive, put B first
usort() is the helper.
The comparison function is the rule you give it.
Syntax and Examples
The basic syntax is:
usort($array, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
Example: sort by price descending
$inventory = array(
array("type" => "fruit", "price" => 3.50),
array("type" => "milk", "price" => 2.90),
array("type" => "pork", "price" => 5.43),
);
usort($inventory, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
print_r($inventory);
Output:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
Why this works
The spaceship operator <=> compares two values.
$b['price'] <=> $a['price']
This means:
- if
$b['price']is bigger, result is positive - if they are equal, result is
0 - if
$b['price']is smaller, result is negative
Because $b is compared to $a, the order becomes descending.
Ascending version
If you want lowest price first:
usort($inventory, function ($a, $b) {
return $a['price'] <=> $b['price'];
});
Older style without <=>
If you are using older PHP code, you may see this:
usort($inventory, function ($a, $b) {
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? 1 : -1;
});
This also sorts by price in descending order.
Step by Step Execution
Consider this code:
$inventory = array(
array("type" => "fruit", "price" => 3.50),
array("type" => "milk", "price" => 2.90),
array("type" => "pork", "price" => 5.43),
);
usort($inventory, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
Step-by-step
1. PHP starts sorting the array
usort() takes control of $inventory and begins comparing pairs of elements.
2. It picks two items
For example, PHP may compare:
$a = array("type" => "fruit", "price" => 3.50);
$b = array("type" => "milk", "price" => 2.90);
3. The comparison function runs
return $b['price'] <=> $a['price'];
This becomes:
2.90 <=> 3.50
Result: -1
That tells PHP the current order should be adjusted so the higher price comes first.
4. PHP compares other pairs
Then it may compare pork with fruit:
5.43 <=> 3.50
Result: 1
That tells PHP pork should come before fruit in descending order.
5. Sorting finishes
After enough comparisons, the final order is:
array(
array("type" => "pork", "price" => 5.43),
array("type" => "fruit", "price" => 3.50),
array("type" => "milk", "price" => 2.90),
)
Important note
You do not control exactly which pairs PHP compares or in what order. You only provide the comparison rule. PHP handles the sorting process.
Real World Use Cases
Sorting arrays of associative arrays is very common in PHP applications.
Common examples
- E-commerce: sort products by price, rating, or stock
- Admin dashboards: sort users by signup date or last login
- Reports: sort rows by revenue, quantity, or score
- API data: sort decoded JSON arrays by a field like
created_atorpriority - Task lists: sort tasks by deadline or importance
Example: sorting products by price
$products = [
['name' => 'Laptop', 'price' => 899.99],
['name' => 'Mouse', 'price' => 19.99],
['name' => 'Monitor', 'price' => 249.99],
];
usort($products, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
Example: sorting users by age
$users = [
['name' => 'Ava', 'age' => 31],
['name' => 'Liam', 'age' => 24],
['name' => 'Noah', 'age' => 28],
];
usort($users, function ($a, $b) {
return $a['age'] <=> $b['age'];
});
Same idea, different field.
Real Codebase Usage
In real projects, developers usually wrap sorting logic in a clear pattern so it is easy to reuse and maintain.
Common patterns
Guard clauses for missing keys
Real data is not always perfect. Some items may not have the key you expect.
usort($inventory, function ($a, $b) {
$priceA = $a['price'] ?? 0;
$priceB = $b['price'] ?? 0;
return $priceB <=> $priceA;
});
This avoids undefined index errors.
Sorting after fetching or decoding data
$data = json_decode($json, true);
usort($data, function ($a, $b) {
return $b['score'] <=> $a['score'];
});
This is common after reading API responses.
Reusable sort function
function sortByPriceDescending(array &$items): void
{
usort($items, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
}
This makes your code cleaner when sorting is needed in multiple places.
Sorting by dynamic field
function sortByFieldDescending(array &$items, string $field): void
{
usort($items, function ($a, $b) use ($field) {
return ($b[$field] ?? 0) <=> ($a[$field] ?? 0);
});
}
This is useful when a controller or service can sort by different columns.
Practical advice
- validate your data before sorting
- use clear field names
- prefer simple comparison functions
- extract the sort into a function if reused
Common Mistakes
1. Using sort() instead of usort()
sort() does not let you compare nested values inside associative arrays.
Broken example:
sort($inventory);
Why it is a problem:
- it sorts using PHP's default rules
- it does not specifically sort by
price
Use usort() when you need custom logic.
2. Returning true or false instead of a comparison value
Broken example:
usort($inventory, function ($a, $b) {
return $a['price'] > $b['price'];
});
Why it is a problem:
usort()expects negative, zero, or positive values- boolean results can lead to incorrect or inconsistent sorting
Correct:
usort($inventory, function ($a, $b) {
return $a['price'] <=> $b['price'];
});
3. Reversing ascending and descending order
Broken logic for descending:
return $a['price'] <=> $b['price'];
This actually sorts ascending.
For descending:
return $b['price'] <=> $a['price'];
4. Forgetting that usort() reindexes the array
After sorting, numeric keys are reset starting from 0.
If you need to preserve keys, usort() is not the right choice.
5. Not handling missing fields
Broken example:
usort($inventory, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
If one item does not contain price, PHP may raise a warning.
Safer version:
usort($inventory, function ($a, $b) {
return ($b['price'] ?? 0) <=> ($a['price'] ?? 0);
});
Comparisons
| Approach | Best for | Preserves keys | Custom field sorting | Notes |
|---|---|---|---|---|
sort() | Simple indexed arrays | No | No | Sorts values directly |
rsort() | Reverse sorting simple indexed arrays | No | No | Descending order only |
asort() | Associative arrays by value | Yes | No | Works on one-level arrays |
ksort() | Associative arrays by key | Yes | No | Sorts by keys, not nested values |
usort() | Indexed arrays with custom rules | No | Yes | Best choice here |
uasort() | Associative arrays with custom rules | Yes | Yes | Useful when keys must stay intact |
usort() vs uasort()
If your array has meaningful keys and you want to keep them, use uasort() instead.
$inventory = [
'a' => ['type' => 'fruit', 'price' => 3.50],
'b' => ['type' => 'milk', 'price' => 2.90],
'c' => ['type' => 'pork', 'price' => 5.43],
];
uasort($inventory, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
usort() vs manual extraction
Another possible approach is extracting the column values first, but for beginners, usort() is usually simpler and clearer for custom sorting logic.
Cheat Sheet
// Descending by price
usort($inventory, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
// Ascending by price
usort($inventory, function ($a, $b) {
return $a['price'] <=> $b['price'];
});
Rules
- Use
usort()for custom sorting of indexed arrays. - The callback receives two elements:
$aand$b. - Return:
- negative if
$ashould come first 0if equal- positive if
$bshould come first
- negative if
<=>is a clean way to compare values.usort()reindexes numeric keys.
Safe version for missing keys
usort($inventory, function ($a, $b) {
return ($b['price'] ?? 0) <=> ($a['price'] ?? 0);
});
Older PHP style
usort($inventory, function ($a, $b) {
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? 1 : -1;
});
Remember
- descending:
$b['field'] <=> $a['field'] - ascending:
$a['field'] <=> $b['field']
FAQ
How do I sort an array of associative arrays by a value in PHP?
Use usort() with a comparison function that compares the desired key, such as price.
How do I sort by price in descending order in PHP?
Use:
usort($inventory, function ($a, $b) {
return $b['price'] <=> $a['price'];
});
How do I sort in ascending order instead?
Swap the comparison order:
return $a['price'] <=> $b['price'];
What does the <=> operator do in PHP?
It is the spaceship operator. It compares two values and returns a negative number, 0, or a positive number.
Does usort() preserve array keys?
No. usort() reindexes the array numerically. Use uasort() if you need to preserve keys.
Can I sort by a string field like type?
Yes.
usort($inventory, function ($a, $b) {
return $a['type'] <=> $b['type'];
});
What if some items do not have the price key?
Use a fallback value with ??.
return ($b['price'] ?? 0) <=> ($a['price'] ?? 0);
Mini Project
Description
Build a small PHP script that sorts a product inventory by price. This project demonstrates how to sort nested associative array data, which is a common task when working with product lists, API results, or report data.
Goal
Create a PHP script that sorts a list of products by price from highest to lowest and prints the sorted result.
Requirements
- Create an array of at least four products using associative arrays.
- Each product must include a
nameandpricefield. - Sort the array in descending order by
price. - Print the sorted array so the new order is visible.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.