How To Sort Array Of Objects By Object Fields In PHP

In PHP, you often work with arrays of objects that need to be sorted based on the values of their object properties. In this tutorial you will learn how to sort an array of objects by object fields in PHP with code examples.

“usort()” Function to Sort an Array of Objects by Object Fields

The usort() function in PHP allows you to sort an array using a custom comparison function. You can define a comparison function that compares the desired object property or field of two objects and sorts the array accordingly. Here’s an example of how to use usort() to sort an array of objects by an object field:

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$people = [
    new Person("Alice", 30),
    new Person("Bob", 25),
    new Person("Charlie", 35),
    new Person("David", 22)
];

// Define a custom comparison function
function compareByAge($a, $b) {
    return $a->age - $b->age;
}

// Sort the array of objects by age
usort($people, "compareByAge");

// Print the sorted array
foreach ($people as $person) {
    echo "Name: " . $person->name . ", Age: " . $person->age . "\n";
}
Name: David, Age: 22
Name: Bob, Age: 25
Name: Alice, Age: 30
Name: Charlie, Age: 35

In this example, we have an array of Person objects, and we want to sort them by the age property.

  • We define a custom comparison function compareByAge($a, $b) that compares the age property of two objects.
  • We then use usort() to sort the array of objects based on this custom comparison function.

PHP “usort()” with Anonymous Functions

In PHP 5.3 and later versions, you can use anonymous functions (also known as closures) to define custom comparison functions directly within the usort() call. This approach is convenient when you need to sort an array of objects by a specific property without defining a separate function.

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$people = [
    new Person("Alice", 30),
    new Person("Bob", 25),
    new Person("Charlie", 35),
    new Person("David", 22)
];

// Sort the array of objects by age using an anonymous function
usort($people, function($a, $b) {
    return $a->age - $b->age;
});

// Print the sorted array
foreach ($people as $person) {
    echo "Name: " . $person->name . ", Age: " . $person->age . "\n";
}

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy