Home >Backend Development >PHP Tutorial >How Can I Sort an Array of Objects in PHP by a Specific Property?
Sorting an Array of Objects by a Property
An array of objects can be encountered in various programming scenarios. These objects possess multiple properties, such as name and count. Organizing these objects based on a specific property can often prove useful.
Customizing the Comparison Function: usort
PHP provides the usort function for sorting arrays. This function allows for the customization of the comparison function used for sorting, enabling you to specify the property by which the objects will be ordered.
The syntax for usort is as follows:
usort($array, $compare_function)
where $array is the array of objects to be sorted and $compare_function is a callable function that defines the comparison logic.
Example: Sorting Objects by Name
Consider the following array of objects:
$array = [ (object) ['name' => 'Mary Jane', 'count' => 420], (object) ['name' => 'Johnny', 'count' => 234], (object) ['name' => 'Kathy', 'count' => 4354], ... ];
To sort the array by name in ascending order, define the following compare function:
function cmp($a, $b) { return strcmp($a->name, $b->name); }
This function compares the names of two objects using the strcmp function, which returns 1 if $a->name is greater than $b->name, -1 if it's less than, and 0 if they're equal.
Finally, invoke usort with the compare function to sort the array:
usort($array, 'cmp');
Alternative Comparison Options
In addition to using custom compare functions, usort supports various other methods for defining the comparison logic, including:
Anonymous functions (PHP 5.3 ):
usort($array, function($a, $b) { return strcmp($a->name, $b->name); });
Class methods:
usort($array, array($this, "cmp"));
Arrow functions (PHP 7.4 ):
usort($array, fn($a, $b) => strcmp($a->name, $b->name));
Sorting Numeric Values
When sorting numeric properties, such as count, you can use the spaceship operator (<=>):
usort($array, fn($a, $b) => $a->count <=> $b->count);
The above is the detailed content of How Can I Sort an Array of Objects in PHP by a Specific Property?. For more information, please follow other related articles on the PHP Chinese website!