Question
How can I sort this PHP array by the value of the order key?
Even though the values are currently sequential, they will not always be.
$array = [
[
'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
'title' => 'Flower',
'order' => 3,
],
[
'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
'title' => 'Free',
'order' => 2,
],
[
'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
'title' => 'Ready',
'order' => 1,
],
];
Short Answer
You will learn how to sort a two-dimensional array in PHP using the value of a specific key such as order. By the end, you will understand how usort() works, how to write a custom comparison function, and how to handle ascending and descending sorts safely.
Concept
In PHP, a two-dimensional array is an array that contains other arrays. When you want to sort it by one field inside each inner array, such as order, you cannot use basic sorting functions like sort() directly in a useful way because they do not know which inner key should control the ordering.
This is where usort() becomes useful. usort() lets you define how two items should be compared. PHP then repeatedly uses that comparison rule to arrange the full array.
For your case, each item looks like this:
[
'hashtag' => '...',
'title' => '...',
'order' => 3
]
If you want to sort by order, your comparison function should compare:
$a['order']
and
$b['order']
This matters in real programming because data often needs custom ordering:
- sorting products by price
- sorting users by age
- sorting tasks by priority
- sorting API results by date
- sorting menu items by display order
Mental Model
Think of each inner array as a card in a stack.
Each card has several labels on it:
hashtagtitleorder
You want to arrange the cards based only on the number written next to order.
usort() is like giving a helper one instruction:
When comparing two cards, put the one with the smaller
ordernumber first.
PHP keeps applying that rule until the whole stack is sorted.
Syntax and Examples
The most common way to sort a 2D array by a key in PHP is with usort().
Basic syntax
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
The <=> operator is called the spaceship operator. It returns:
-1if left is smaller0if both are equal1if left is greater
That is exactly what usort() needs.
Example: ascending order
$array = [
['hashtag' => 'a7e...', 'title' => 'Flower', 'order' => 3],
['hashtag' => 'b24...', 'title' => 'Free', 'order' => ],
[ => , => , => ],
];
(, function (, ) {
[] <=> [];
});
();
Step by Step Execution
Consider this code:
$array = [
['title' => 'Flower', 'order' => 3],
['title' => 'Free', 'order' => 2],
['title' => 'Ready', 'order' => 1],
];
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
Here is what happens step by step:
- PHP starts sorting the array.
- It picks two items to compare.
- The callback receives them as
$aand$b. - It compares
$a['order']and$b['order']. - If
$a['order']is smaller, it returns-1, so$ashould come first. - If they are equal, it returns
0, so their relative position does not need to change.
Real World Use Cases
Sorting a 2D array by a key is common in many PHP applications.
Typical use cases
- Menu items sorted by display order
- Tasks sorted by priority
- Blog posts sorted by publish date or rank
- Products sorted by price or stock level
- API responses sorted before sending data to the frontend
- Form fields sorted by custom position
Example: sorting menu items
$menu = [
['label' => 'Contact', 'order' => 3],
['label' => 'Home', 'order' => 1],
['label' => 'About', 'order' => 2],
];
usort($menu, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
This ensures the menu appears in the intended order.
Example: sorting products by price
$products = [
['name' => , => ],
[ => , => ],
[ => , => ],
];
(, function (, ) {
[] <=> [];
});
Real Codebase Usage
In real projects, developers usually sort arrays after fetching data from:
- a database
- an external API
- a config file
- user input
Common patterns
1. Sorting by a configurable field
$sortKey = 'order';
usort($array, function ($a, $b) use ($sortKey) {
return $a[$sortKey] <=> $b[$sortKey];
});
This is useful when the sort key can change.
2. Guarding against missing keys
usort($array, function ($a, $b) {
$aValue = $a['order'] ?? PHP_INT_MAX;
$bValue = $b['order'] ?? PHP_INT_MAX;
return $aValue <=> $bValue;
});
This avoids errors if some items do not have an order value.
3. Early data cleanup before sorting
Common Mistakes
1. Using sort() instead of usort()
Broken example:
sort($array);
Why it is a problem:
sort()does not let you choose a nested key likeorder- it compares whole values in a way that is usually not what you want
Use this instead:
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
2. Returning true or false from the callback
Broken example:
usort($array, function ($a, $b) {
return $a['order'] > [];
});
Comparisons
| Function | Use case | Custom key comparison | Preserves keys |
|---|---|---|---|
sort() | Simple indexed arrays | No | No |
rsort() | Reverse simple indexed arrays | No | No |
usort() | Indexed arrays with custom comparison | Yes | No |
asort() | Sort by values while preserving keys | No | Yes |
uasort() | Custom comparison while preserving keys | Yes | Yes |
Cheat Sheet
Sort a 2D array by key in PHP
Ascending
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
Descending
usort($array, function ($a, $b) {
return $b['order'] <=> $a['order'];
});
Preserve original keys
uasort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
Handle missing keys safely
usort($array, function ($a, ) {
([] ?? PHP_INT_MAX) <=> ([] ?? PHP_INT_MAX);
});
FAQ
How do I sort a multidimensional array by one key in PHP?
Use usort() with a callback that compares the chosen key:
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
How do I sort in descending order in PHP?
Reverse the comparison:
usort($array, function ($a, $b) {
return $b['order'] <=> $a['order'];
});
What is the difference between usort() and uasort()?
usort() reindexes numeric keys. uasort() preserves the original keys.
Can I sort by a string key like title instead of order?
Mini Project
Description
Build a small PHP script that sorts a list of tasks by priority. Each task should be stored as an associative array inside a larger array. This project demonstrates how to sort real structured data by one column, which is a common need in apps such as task managers, admin dashboards, and content systems.
Goal
Create a PHP program that sorts a list of tasks by their priority value from lowest to highest and prints the sorted result.
Requirements
- Create an array containing at least four tasks
- Each task must include
titleandprioritykeys - Sort the array by
priorityin ascending order - Print the sorted tasks in a readable format
Keep learning
Related questions
Converting HTML and CSS to PDF in PHP: Core Concepts, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose practical approaches for reliable PDF output.
How PHP foreach Actually Works with Arrays
Learn how PHP foreach works internally, including array copies, internal pointers, by-value vs by-reference behavior, and common pitfalls.
How to Check String Prefixes and Suffixes in PHP
Learn how to check whether a string starts or ends with specific text in PHP using simple functions and practical examples.