Sorting an Array of Objects in PHP: By One Property for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Sorting an Array of Objects in PHP: From Chaos to Order in 5 Minutes

\n\n

Imagine: you're writing a PHP educational website and you've received a list of students from the database. Each student is an object with a name, age, and score. You need to display them on the page: first the oldest, or conversely, the youngest. Or, maybe, sort them alphabetically. How do you do this if you don't have a simple array of numbers, but an array of objects?

\n\n

This question is one of the most popular on Stack Overflow. Thousands of developers, from beginners to pros, face the task of "sort array of objects by one property". And today we'll break it down once and for all. No fluff, with live examples and clear explanations.

\n\n

Why doesn't the regular sort() work?

\n\n

Let's say we have an array of objects $students:

\n\n
<?php\nclass Student {\n    public $name;\n    public $age;\n    public $score;\n\n    public function __construct($name, $age, $score) {\n        $this->name = $name;\n        $this->age = $age;\n        $this->score = $score;\n    }\n}\n\n$students = [\n    new Student("Anna", 22, 85),\n    new Student("Ivan", 20, 92),\n    new Student("Maria", 23, 78),\n    new Student("Peter", 21, 95)\n];\n?>
\n\n

If you try to call sort($students), PHP will throw an error or simply do nothing. Why? Because sort() knows how to compare numbers and strings, but doesn't know how to compare two objects. You need to explain to it: "Compare by the age property" or "Compare by name". For this, PHP has a special function — usort().

\n\n

Meet usort(): Your Main Tool

\n\n

The usort() function takes two arguments: the array itself and a comparison function. This comparison function must return:

\n
    \n
  • 0, if the elements are equal;
  • \n
  • a negative number, if the first element is less than the second;
  • \n
  • a positive number, if the first element is greater than the second.
  • \n
\n\n

Sounds complicated? In practice, it's simple. Let's sort the students by age (ascending):

\n\n
<?php\nusort($students, function($a, $b) {\n    return $a->age <=> $b->age;\n});\n\n// Result: Ivan (20), Peter (21), Anna (22), Maria (23)\n?>
\n\n

Notice the <=> operator (spaceship). It was introduced in PHP 7 and makes sorting extremely concise. It compares two values and returns -1, 0, or 1. Exactly what usort() needs.

\n\n

Sorting in Descending Order: Swap the Sign

\n\n

Want to sort from oldest to youngest? Simply swap the operands in the <=> operator:

\n\n
<?php\nusort($students, function($a, $b) {\n    return $b->age <=> $a->age;  // now b is compared to a\n});\n\n// Result: Maria (23), Anna (22), Peter (21), Ivan (20)\n?>
\n\n

Or, equivalently, multiply the result by -1:

\n\n
<?php\nusort($students, function($a, $b) {\n    return -($a->age <=> $b->age);\n});\n?>
\n\n

Sorting by Strings (Alphabetically)

\n\n

What if the property is a string? For example, a name. Same principle, but instead of <=> we use strcmp() or strcasecmp() (for case-insensitive comparison):

\n\n
<?php\n// Alphabetically (A-Z)\nusort($students, function($a, $b) {\n    return strcmp($a->name, $b->name);\n});\n\n// Result: Anna, Ivan, Maria, Peter\n\n// Alphabetically (Z-A) — reverse order\nusort($students, function($a, $b) {\n    return strcmp($b->name, $a->name);\n});\n?>
\n\n

Sorting by a Numeric Property: Alternative to <=>

\n\n

The <=> operator is convenient, but if you're working with older PHP (before 7.0), it doesn't exist. In that case, write the comparison manually:

Blogs

Book Recommendations