PHP
Custom Sorting Arrays of Objects/Associative Arrays
Learn how to use `usort` in PHP to sort arrays of complex data structures like objects or associative arrays based on a custom comparison logic.
<?php
$users = [
['name' => 'Charlie', 'age' => 30],
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 35],
];
// Sort users by age in ascending order
usort($users, function($a, $b) {
return $a['age'] <=> $b['age']; // PHP 7+ spaceship operator
// For PHP < 7:
// if ($a['age'] == $b['age']) return 0;
// return ($a['age'] < $b['age']) ? -1 : 1;
});
echo "Sorted by age (ascending):
";
print_r($users);
class Product {
public $id;
public $name;
public $price;
public function __construct($id, $name, $price) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
}
}
$products = [
new Product(1, 'Banana', 1.20),
new Product(2, 'Apple', 0.80),
new Product(3, 'Orange', 1.50),
];
// Sort products by name in alphabetical order
usort($products, function($a, $b) {
return strcmp($a->name, $b->name);
});
echo "
Sorted by product name (alphabetical):
";
print_r($products);
?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. This is particularly useful for complex data structures like arrays of associative arrays or objects, allowing developers to define custom sorting logic based on specific keys, properties, or any other comparison criteria, giving precise control over the order.