Question
How to Sort an Array of Objects by Property in PHP
Question
How can I sort a PHP array of objects by one of its properties, such as name or count?
Example data:
$array = [
(object) [
'ID' => 1,
'name' => 'Mary Jane',
'count' => 420,
],
(object) [
'ID' => 2,
'name' => 'Johnny',
'count' => 234,
],
(object) [
'ID' => 3,
'name' => 'Kathy',
'count' => 4354,
],
];
I want to sort the array by a chosen field like name or count. What is the correct way to do this in PHP?
Short Answer
By the end of this page, you will understand how to sort an array of objects in PHP by a specific property using usort(). You will learn how comparison functions work, how to sort strings and numbers, how ascending and descending order differ, and how this pattern is used in real PHP codebases.
Concept
In PHP, an array of objects is a normal array where each item is an object. To sort that array by one object property, you usually use usort().
usort() lets you define how two items should be compared. PHP repeatedly calls your comparison function and rearranges the array based on the result.
Your comparison function must return:
- a negative number if the first item should come before the second
0if they are equal- a positive number if the first item should come after the second
This matters because arrays of objects are very common in real programs:
- database results turned into objects
- API responses mapped into objects
- collections of users, products, or orders
- reports sorted by totals, names, or timestamps
When sorting objects, the main question is: which property should decide the order?
For example:
- sort by
namealphabetically - sort by
countnumerically - sort by
IDascending
In modern PHP, the spaceship operator <=> makes comparisons much cleaner. It returns exactly the kind of value usort() needs.
Mental Model
Think of usort() as hiring a judge to compare two objects at a time.
The judge does not sort the whole array at once. Instead, PHP keeps asking questions like:
- Should
Mary Janecome beforeJohnny? - Should
Johnnycome beforeKathy? - Should
420come before234?
Your comparison function is the judge's rulebook.
If you say:
- compare
$a->namewith$b->name, PHP sorts alphabetically - compare
$a->countwith$b->count, PHP sorts numerically
So the key idea is:
usort()does the sorting work- you provide the rule for comparing two objects
Syntax and Examples
The basic syntax is:
usort($array, function ($a, $b) {
return $a->property <=> $b->property;
});
Sort by a numeric property
usort($array, function ($a, $b) {
return $a->count <=> $b->count;
});
This sorts the objects by count in ascending order.
Sort by a string property
usort($array, function ($a, $b) {
return $a->name <=> $b->name;
});
This sorts the objects by name alphabetically.
Full example
$array = [
(object) ['ID' => , => , => ],
() [ => , => , => ],
() [ => , => , => ],
];
(, function (, ) {
->name <=> ->name;
});
();
Step by Step Execution
Consider this example:
$array = [
(object) ['name' => 'Mary Jane', 'count' => 420],
(object) ['name' => 'Johnny', 'count' => 234],
(object) ['name' => 'Kathy', 'count' => 4354],
];
usort($array, function ($a, $b) {
return $a->count <=> $b->count;
});
What happens step by step:
-
PHP starts sorting the array.
-
It picks two objects to compare.
-
The callback receives them as
$aand$b. -
It evaluates:
$a->count <=> $b->count -
If
$a->countis smaller, the callback returns a negative number.
Real World Use Cases
Sorting arrays of objects by property is used constantly in PHP applications.
Common examples
- User lists: sort users by name, age, or signup date
- Product catalogs: sort products by price, rating, or stock count
- Admin dashboards: sort records by newest first or highest total
- Reports: sort rows by sales count or revenue
- API responses: reorder fetched objects before returning JSON
- Search results: sort by relevance score or alphabetically
Example: sort products by price
usort($products, function ($a, $b) {
return $a->price <=> $b->price;
});
Example: sort users by last name
usort($users, function ($a, $b) {
return $a->lastName <=> $b->lastName;
});
Real Codebase Usage
In real projects, developers rarely hardcode sorting in only one place. They often build reusable sorting patterns.
1. Sorting by a requested field
$allowedFields = ['name', 'count', 'ID'];
$field = $_GET['sort'] ?? 'name';
if (!in_array($field, $allowedFields, true)) {
$field = 'name';
}
usort($array, function ($a, $b) use ($field) {
return $a->$field <=> $b->$field;
});
This uses validation so the code only sorts by safe, expected properties.
2. Guard clauses for missing data
usort($array, function ($a, $b) {
$aValue = $a->count ?? 0;
$bValue = $b->count ?? ;
<=> ;
});
Common Mistakes
1. Using sort() instead of usort()
sort() does not let you compare object properties directly.
Broken idea:
sort($array);
Use:
usort($array, function ($a, $b) {
return $a->name <=> $b->name;
});
2. Forgetting that usort() reindexes the array
After sorting, numeric keys are reset.
If you need to preserve keys, usort() is not the right tool.
3. Returning true or false instead of a comparison value
Broken code:
usort($array, function ($a, $b) {
->count > ->count;
});
Comparisons
| Approach | Best for | Example | Notes |
|---|---|---|---|
usort() | Sorting arrays with custom rules | Sort objects by name | Most common choice for object property sorting |
sort() | Simple value arrays | Sort [3, 1, 2] | Not suitable for object-property comparisons |
uasort() | Custom sorting while preserving keys | Sort associative arrays of objects | Similar to usort(), but keeps original keys |
ksort() | Sorting by array keys | Sort by ID keys in an associative array |
Cheat Sheet
// Sort by numeric property ascending
usort($items, function ($a, $b) {
return $a->count <=> $b->count;
});
// Sort by numeric property descending
usort($items, function ($a, $b) {
return $b->count <=> $a->count;
});
// Sort by string property ascending
usort($items, function ($a, $b) {
return $a->name <=> $b->name;
});
// Sort by dynamic property
$field = 'name';
usort($items, function ($a, $b) use ($field) {
return $a->$field <=> $b->$field;
});
// Case-insensitive string sort
usort($items, function ($a, $b) {
(->name) <=> (->name);
});
(, function (, ) {
(->count ?? ) <=> (->count ?? );
});
FAQ
How do I sort an array of objects alphabetically in PHP?
Use usort() and compare the string property:
usort($array, fn($a, $b) => $a->name <=> $b->name);
How do I sort an array of objects by a number in PHP?
Compare the numeric property with <=>:
usort($array, fn($a, $b) => $a->count <=> $b->count);
How do I sort in descending order?
Reverse the comparison:
usort($array, fn($a, $b) => $b->count <=> $a->count);
Can I sort by a property name stored in a variable?
Yes.
$field = 'name';
usort(, fn(, ) => -> <=> ->);
Mini Project
Description
Build a small PHP script that sorts a list of products by different object properties such as name, price, or stock. This demonstrates how real applications let users choose how data should be ordered.
Goal
Create a reusable function that sorts an array of objects by a selected property in ascending or descending order.
Requirements
- Create an array of at least 4 product objects
- Allow sorting by
name,price, orstock - Support both ascending and descending order
- Print the sorted result clearly
- Handle invalid sort fields safely
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.