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' => 1, 'name' => 'Mary Jane', 'count' => 420],
(object) ['ID' => 2, 'name' => 'Johnny', 'count' => 234],
(object) ['ID' => 3, 'name' => 'Kathy', 'count' => 4354],
];
usort($array, function ($a, $b) {
return $a->name <=> $b->name;
});
print_r($array);
Result order:
Johnny
Kathy
Mary Jane
Descending order
Swap the values:
usort($array, function ($a, $b) {
return $b->count <=> $a->count;
});
Now larger count values come first.
Dynamic property sorting
If the property name is stored in a variable:
$field = 'count';
usort($array, function ($a, $b) use ($field) {
return $a->$field <=> $b->$field;
});
This is useful when the user chooses the sort field.
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. -
PHP places
$abefore$b. -
If the counts are equal, the callback returns
0. -
PHP treats them as equal for sorting.
-
PHP repeats this process until the whole array is ordered.
With the sample data:
- compare
420and234→420is greater, soJohnnyshould come first - compare
420and4354→420is smaller, soMary Janestays beforeKathy - final order becomes
Johnny,Mary Jane,Kathywhen sorted bycount
You can verify it:
foreach ($array as $item) {
echo $item->name . ' - ' . $item->count . PHP_EOL;
}
Output:
Johnny - 234
Mary Jane - 420
Kathy - 4354
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 ?? 0;
return $aValue <=> $bValue;
});
This avoids errors when some objects do not have the property.
3. Descending sort for dashboards
usort($orders, function ($a, $b) {
return $b->total <=> $a->total;
});
This is common when showing highest values first.
4. Sorting after fetching data
Sometimes data comes from a database already sorted, but if not, PHP sorting is still useful for:
- transformed data
- merged data from multiple sources
- temporary in-memory collections
- custom business rules not handled by SQL easily
5. Encapsulating sort logic in a function
function sortByField(array &$items, string $field): void
{
usort($items, function ($a, $b) use ($field) {
return $a->$field <=> $b->$field;
});
}
This keeps controllers and services cleaner.
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) {
return $a->count > $b->count;
});
This may appear to work sometimes, but it is not the correct contract.
Correct code:
usort($array, function ($a, $b) {
return $a->count <=> $b->count;
});
4. Mixing string and numeric logic carelessly
If count is stored as a string like '420', comparisons may still work, but inconsistent data can cause confusion. It is better to keep numeric fields numeric.
usort($array, function ($a, $b) {
return (int) $a->count <=> (int) $b->count;
});
5. Not handling missing properties
Broken code:
usort($array, function ($a, $b) {
return $a->score <=> $b->score;
});
If score does not exist on every object, this can produce notices or incorrect behavior.
Safer version:
usort($array, function ($a, $b) {
return ($a->score ?? 0) <=> ($b->score ?? 0);
});
6. Forgetting case sensitivity in string sorting
Alphabetical sorting can behave unexpectedly if names have mixed uppercase and lowercase letters.
usort($array, function ($a, $b) {
return strtolower($a->name) <=> strtolower($b->name);
});
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 | Sorts keys, not object properties |
usort() vs uasort()
| Feature | usort() | uasort() |
|---|---|---|
| Custom comparison callback | Yes | Yes |
| Reindexes numeric keys | Yes | No |
| Good for plain lists | Yes | Yes |
| Good when keys matter | No | Yes |
Ascending vs descending
| Order | Comparison |
|---|---|
| Ascending | $a->count <=> $b->count |
| Descending | $b->count <=> $a->count |
String vs numeric sorting
| Property type | Typical comparison |
|---|---|
| Number | $a->count <=> $b->count |
| String | $a->name <=> $b->name |
| Case-insensitive string | strtolower($a->name) <=> strtolower($b->name) |
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) {
return strtolower($a->name) <=> strtolower($b->name);
});
// Handle missing properties safely
usort($items, function ($a, $b) {
return ($a->count ?? 0) <=> ($b->count ?? 0);
});
Rules to remember
- Use
usort()for custom sorting of array values. - The callback compares two items at a time.
- Return negative, zero, or positive.
- Use
<=>for clean comparisons. - Swap left and right to reverse the order.
usort()resets numeric keys.- Use
uasort()if keys must be preserved.
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($array, fn($a, $b) => $a->$field <=> $b->$field);
What if some objects do not have that property?
Use a fallback value:
usort($array, fn($a, $b) => ($a->count ?? 0) <=> ($b->count ?? 0));
Does usort() keep the original array keys?
No. It reindexes the array. Use uasort() if you need to preserve keys.
Should I sort in PHP or in SQL?
If the data comes from a database, sorting in SQL is often better for large datasets. Sorting in PHP is useful when the data is already loaded or when the sort rule is custom.
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.