"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to sort an array of objects according to specific attributes in PHP?

How to sort an array of objects according to specific attributes in PHP?

Posted on 2025-04-15
Browse:524

How Can I Sort an Array of Objects in PHP Based on a Specific Property?

Ordering an Array of Objects Based on a Specific Property

When handling arrays of objects, sorting them based on specific fields can be essential for data management. To accomplish this, one can utilize the usort function, which enables the customization of the comparison behavior.

Custom Comparison Function with usort:

To define a custom comparison function in usort, follow this pattern:

function cmp($a, $b) {
    return strcmp($a->name, $b->name);
}

usort($your_data, "cmp");

In this example, the comparison is based on the "name" property of the objects. You can replace "name" with any relevant property.

Alternative Callback Options:

Apart from using a dedicated function, usort also accepts any callable as the second argument. Here are some alternatives:

  • Anonymous Function (PHP 5.3 ):
usort($your_data, function($a, $b) {
    return strcmp($a->name, $b->name);
});
  • Class Method:
usort($your_data, array($this, "cmp")); // where "cmp" is a method in the class
  • Arrow Function (PHP 7.4 ):
usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));

Comparing Numeric Values:

When ordering objects based on numeric properties, consider the following comparison function:

fn($a, $b) => $a->count - $b->count

Alternatively, in PHP 7 , you can use the Spaceship operator for succinct comparisons:

fn($a, $b) => $a->count  $b->count
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3