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:
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:
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" => );
= ( => , => );
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
= [
[ => , => ],
[ => , => ],
[ => , => ],
];
(, function (, ) {
[] <=> [];
});
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
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
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 |
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
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.
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.