How to Sort Array of Objects by Property in PHP

Summary:

Sorting a PHP array of objects by a specific property can easily be handled by using PHP's function usort($array, callback($a, $b){ //sorting logic }). It takes 2 parameters, the array to be sorted and a callback function where the sorting logic is performed.

Sort Array of Objects by Property in PHP

The article answers how to sort array of objects by property in PHP. Here’s a quick overview of the solution.

$employees_arr =
[
    new Employee('5', 'Brian', 90000, '25'),
    new Employee('1', 'Allen', 60000, '29'),
    new Employee('2', 'Kylie', 50000, '27'),
    new Employee('3', 'Jeane', 80000, '35'),
    new Employee('4', 'Franklin', 75000, '30'),
];
 
 
//Sorts the array by the property salary
usort($employees_arr, function($a, $b)
{
    return $a->salary - $b->salary;
});

If the code doesn’t make sense to you now, don’t worry! Just stick with the article to the end, and you’ll be able to understand all about the code above and perhaps a couple of other interesting PHP stuff!

Plus, the article now includes sorting based on two or more properties. Check that out as well.

Relevant Content: PHP usort Function

The article uses the usort function to sort array of objects by property value in PHP. The usort is a higher order function that expects an array and a callback function. The callback function gives a lot of room to define custom sorting logic. 

usort(array &$array, callable $callback): bool

The callback function compares two arguments, $a and $b, and returns an integer as follows.

  • Less than zero if $a is less than $b.
  • Equals to zero if  $a is equal to $b
  • Greater than zero if $a is greater than $b.

Basic Usage

Let’s understand the usort function with a basic example. Let’s start small with an array of two numbers and then scale up later.


$numbers = [100, 10];
 
usort($numbers, function($a, $b)
{
    return $a - $b; //Returns the difference. It could be less than, greater than or equal to zero
});
 
//OUTPUT
//[10, 100]

The user-defined function is the most crucial part. The image below describes it.

sort array of objects by property in PHP

The callback return value is 1, which indicates to the usort that $a is greater than $b.

Alternate Syntax

PHP 7.4 and above supports the arrow function. It is more concise but completely optional. Just in case you want to use it – here’s how to.

usort($numbers, fn($a, $b) => $a - $b);

Next, let’s set up the array of objects for sorting.

Scenario: Employee Class in PHP

Background and Setup: Employee Objects Array in PHP

Classes and objects are fundamentals of object oriented programming (OOP). In short, a class is a blueprint that defines an entity’s properties and actions, and an object is an instance or a realisation of that class. Think of a class as a building’s master plan. The object could be a building based on that master plan.

The following is an example of a class in PHP. 

class Employee
{
    public $id;
    public $name;
    public $salary;
    public $age;
 
    function __construct($id, $name, $salary, $age)
    {
        $this->id   = $id;
        $this->name = $name;
        $this->salary = $salary; //$ per annum
        $this->age = $age;
    }
}

The syntax above may seem weird if you’re unaware of PHP OOP. To grasp these fundamentals well, consider reading FuelingPHP’s, ‘How to create a class?’. The article overviews all the fundamentals.

$employees_arr =
[
    new Employee('5', 'Brian', 90000, '25'),
    new Employee('1', 'Allen', 60000, '29'),
    new Employee('2', 'Kylie', 50000, '27'),
    new Employee('3', 'Jeane', 80000, '35'),
    new Employee('4', 'Franklin', 75000, '30'),
];

There are a bunch of properties of an employee object, and we’ll sort them by ‘Salary’. We won’t be reinventing the wheel but use PHP usort function. So, the upcoming section reviews that function.

Option1: How to Sort Array of Objects by Property in PHP

Now, as we are familiar with the usort function, it is time to look at the code to see how to sort array of objects by value in PHP.

Before Sorting

Here’s what the array looks like before sorting. The objective is to sort the array in ascending order by the property ‘Salary’

Array
(
    [0] => Employee Object
        (
            [id] => 5
            [name] => Brian
            [salary] => 90000
            [age] => 25
        )
 
    [1] => Employee Object
        (
            [id] => 1
            [name] => Allen
            [salary] => 60000
            [age] => 29
        )
 
    [2] => Employee Object
        (
            [id] => 2
            [name] => Kylie
            [salary] => 50000
            [age] => 27
        )
 
    [3] => Employee Object
        (
            [id] => 3
            [name] => Jeane
            [salary] => 80000
            [age] => 35
        )
 
    [4] => Employee Object
        (
            [id] => 4
            [name] => Franklin
            [salary] => 75000
            [age] => 30
        )
 
)

Sorting in the Ascending Order

usort($employees_arr, function($a, $b)
{
    return $a->salary - $b->salary;
});

The short snippet of code does alot, and if you are familiar with the usort function, it will make sense to you now. The callback function returns what the usort needs for correctly sorting the array. Recall the numbers example we have seen above 🙂

After Sorting

The lines of code above sort an array of objects by property value, ‘Salary’ and here is it after sorting.

Array
(
    [0] => Employee Object
        (
            [id] => 2
            [name] => Kylie
            [salary] => 50000
            [age] => 27
        )
 
    [1] => Employee Object
        (
            [id] => 1
            [name] => Allen
            [salary] => 60000
            [age] => 29
        )
 
    [2] => Employee Object
        (
            [id] => 4
            [name] => Franklin
            [salary] => 75000
            [age] => 30
        )
 
    [3] => Employee Object
        (
            [id] => 3
            [name] => Jeane
            [salary] => 80000
            [age] => 35
        )
 
    [4] => Employee Object
        (
            [id] => 5
            [name] => Brian
            [salary] => 90000
            [age] => 25
        )
 
)

The employees now appear in the order of increasing salary. For decreasing order, make an inverse of the callback function as.

usort($employees_arr, function($a, $b)
{
    return $b->salary - $a->salary;
});

Voila! The callback function does all the magic. You can use any other PHP function as a callback too. So, as long as you understand the basics, the rest is up to you.

Option2: PHP Sort Array of Objects by Two Properties

We have already seen how to sort array of objects by value in PHP. Let’s step up the game and see how to sort based on two properties – primary and secondary. So, when primary properties are equal, we do a sort based on the secondary property.

The employee objects example is good enough to use here as well. Let “salary” be the primary property and “age” secondary.

Let’s add another employee to the array.

$employees_Arr[] = new Employee('6', 'Alison', 90000, '24');

With that done, let’s see how PHP sort array of objects by two properties.

usort($employees_arr, function($a, $b) {
    $diff = $a->salary - $b->salary;

    return ($diff !== 0) ? $diff : $a->age - $b->age;
});

The callback function calculates the difference in salaries. If the difference is equal to zero, meaning that the two salaries are equal, the function returns the difference in ages. The difference integer determines the sorting order, as the article explains above.

After Sorting

The sorted array is as follows.

Array
(
    [0] => Employee Object
        (
            [id] => 2
            [name] => Kylie
            [salary] => 50000
            [age] => 27
        )

    [1] => Employee Object
        (
            [id] => 1
            [name] => Allen
            [salary] => 60000
            [age] => 29
        )

    [2] => Employee Object
        (
            [id] => 4
            [name] => Franklin
            [salary] => 75000
            [age] => 30
        )

    [3] => Employee Object
        (
            [id] => 3
            [name] => Jeane
            [salary] => 80000
            [age] => 35
        )

    [4] => Employee Object
        (
            [id] => 6
            [name] => Alison
            [salary] => 90000
            [age] => 24
        )

    [5] => Employee Object
        (
            [id] => 5
            [name] => Brian
            [salary] => 90000
            [age] => 25
        )

)

Observe that Brian and Alison have the same salaries, but Alison is younger than Brian. This sort is ascending.

Option3: PHP Sort Array of Objects by Multiple Properties

We have seen PHP sort array of objects by two properties. Let’s take a step further and extend to sorting on multiple properties. For that, let’s add a new property, “Experience”, to the Employee class.

With that change in place, here’s the array of objects now.

$employees_arr =
[
    new Employee('5', 'Brian', 90000, '25', '2'),
    new Employee('1', 'Allen', 60000, '29', '5'),
    new Employee('2', 'Kylie', 50000, '27', '3'),
    new Employee('3', 'Jeane', 80000, '35', '9'),
    new Employee('4', 'Franklin', 75000, '30', '7'),
    new Employee('6', 'Alison', 90000, '24', '1.5'),
    new Employee('7', 'Stuart', 90000, '24', '1'),
];

Let’s do sorting based on salary, age and experience.

usort($employees_arr, function($a, $b) {
     return [$a->salary, $a->age, $a->experience] <=> [$b->salary, $b->age, $b->experience];
});

The <=> is the spaceship operator in PHP available since version 7. Learn more about the spaceship operator.

The spaceship operators compare the two arrays and return -1, 0 or 1.

After Sorting

Here’s the sorted array.

Array
(
    [0] => Employee Object
        (
            [id] => 2
            [name] => Kylie
            [salary] => 50000
            [age] => 27
            [experience] => 3
        )

    [1] => Employee Object
        (
            [id] => 1
            [name] => Allen
            [salary] => 60000
            [age] => 29
            [experience] => 5
        )

    [2] => Employee Object
        (
            [id] => 4
            [name] => Franklin
            [salary] => 75000
            [age] => 30
            [experience] => 7
        )

    [3] => Employee Object
        (
            [id] => 3
            [name] => Jeane
            [salary] => 80000
            [age] => 35
            [experience] => 9
        )

    [4] => Employee Object
        (
            [id] => 7
            [name] => Stuart
            [salary] => 90000
            [age] => 24
            [experience] => 1
        )

    [5] => Employee Object
        (
            [id] => 6
            [name] => Alison
            [salary] => 90000
            [age] => 24
            [experience] => 1.5
        )

    [6] => Employee Object
        (
            [id] => 5
            [name] => Brian
            [salary] => 90000
            [age] => 25
            [experience] => 2
        )

)

Voila! That’s all for now. Let’s wrap up.

Conclusion – Sort Array of Objects by Property in PHP

Wrap Up

This article explains how to sort array of objects by property in PHP. The solution uses the PHP usort function, which is a higher order function expecting a callback. The callback is the most crucial determinant of the sorting, and the article explains it in depth.

Firstly, the article sorts the array of objects by property in PHP. Secondly, it moves on to sorting by two properties and finally by multiple properties.

Hopefully, you’ve enjoyed the article. Stay tuned for more articles like these at FuelingPHP.

Classes and Functions Mentioned

usort – (PHP 4, 5, 7, 8) This core PHP function expects a user-defined callback function for sorting arrays. It has been available since the fourth version of PHP and remains stable. Based on its utility, it seems the function will also stay in future versions.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems