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
Knowing how to sort by a nested value is a very common PHP skill.
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' => 2],
['hashtag' => 'e7d...', 'title' => 'Ready', 'order' => 1],
];
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
print_r($array);
Result:
Array
(
[0] => Array
(
[hashtag] => e7d...
[title] => Ready
[order] => 1
)
[1] => Array
(
[hashtag] => b24...
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => a7e...
[title] => Flower
[order] => 3
)
)
Example: descending order
usort($array, function ($a, $b) {
return $b['order'] <=> $a['order'];
});
Older style comparison
If you are not using the spaceship operator, you may see this:
usort($array, function ($a, $b) {
if ($a['order'] == $b['order']) {
return 0;
}
return ($a['order'] < $b['order']) ? -1 : 1;
});
This works too, but the spaceship version is shorter and clearer.
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. - If
$a['order']is larger, it returns1, so$bshould come first. - PHP repeats this process until the whole array is sorted.
Small comparison trace
Suppose PHP compares:
['title' => 'Flower', 'order' => 3]
and
['title' => 'Free', 'order' => 2]
Then:
3 <=> 2
returns:
1
That means the first item should come after the second one.
Next, if it compares:
2 <=> 1
it returns 1 again, so the item with order = 1 moves earlier.
Final order becomes:
- Ready
- Free
- Flower
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' => 'Phone', 'price' => 699],
['name' => 'Case', 'price' => 29],
['name' => 'Charger', 'price' => 19],
];
usort($products, function ($a, $b) {
return $a['price'] <=> $b['price'];
});
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
$array = array_filter($array, function ($item) {
return isset($item['order']);
});
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
This is a common pattern when input data may be incomplete.
4. Sorting before rendering a view
Developers often sort arrays right before looping over them in templates or controllers so the output is predictable.
5. Reindexing behavior
usort() reindexes numeric keys. In many codebases, that is fine. But if preserving original keys matters, developers often use uasort() instead.
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'] > $b['order'];
});
Why it is a problem:
usort() expects:
- negative number
- zero
- positive number
A boolean is not the proper comparison result.
Correct version:
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
3. Forgetting that values may be strings
If order comes from a form or API, it may be a string like '10'.
Safer version:
usort($array, function ($a, $b) {
return (int)$a['order'] <=> (int)$b['order'];
});
4. Not handling missing keys
Broken example:
usort($array, function ($a, $b) {
return $a['order'] <=> $b['order'];
});
If one item has no order, this can cause warnings.
Safer version:
usort($array, function ($a, $b) {
$aOrder = $a['order'] ?? PHP_INT_MAX;
$bOrder = $b['order'] ?? PHP_INT_MAX;
return $aOrder <=> $bOrder;
});
5. Expecting original numeric keys to stay the same
usort() reindexes the array from 0, 1, 2...
If you need to preserve keys, use uasort().
uasort($array, function ($a, $b) {
return $a['order'] <=> $b['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 |
ksort() | Sort by array keys | No | Yes |
usort() vs uasort()
- Use
usort()when key preservation does not matter. - Use
uasort()when you want to keep the original array keys.
Spaceship operator vs manual comparison
| Approach | Example | Best for |
|---|---|---|
| Spaceship operator | $a['order'] <=> $b['order'] | Most modern PHP code |
| Manual comparison | if ($a['order'] == $b['order']) return 0; | Older PHP versions or explicit logic |
Sorting numbers vs sorting strings
| Data type | Example value | Recommendation |
|---|---|---|
| Integer | 3 | Compare directly |
| Numeric string | '3' | Cast to (int) if needed |
| Text | 'Flower' | Use string comparison or functions like strcmp() |
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, $b) {
return ($a['order'] ?? PHP_INT_MAX) <=> ($b['order'] ?? PHP_INT_MAX);
});
Cast values to integers
usort($array, function ($a, $b) {
return (int)$a['order'] <=> (int)$b['order'];
});
Important rules
usort()sorts the original array in place.usort()reindexes numeric keys.- The callback must return a negative number,
0, or a positive number. - Use
<=>for clean comparisons. - Use
uasort()if you must preserve keys.
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?
Yes. For example:
usort($array, function ($a, $b) {
return strcmp($a['title'], $b['title']);
});
Does usort() return a new array?
No. It sorts the existing array directly.
What happens if two items have the same order value?
The comparison returns 0, meaning they are considered equal for sorting. Their final relative order should not be relied on unless you add a secondary comparison.
Should I cast order to an integer?
If the values may come from forms, JSON, or databases as strings, casting to (int) is a good idea.
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
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.