How can the usort function be utilized to sort multidimensional arrays in PHP effectively?
When sorting multidimensional arrays in PHP, the usort function can be utilized effectively by defining a custom comparison function that compares the desired elements within the subarrays. This allows for flexibility in sorting based on specific criteria within the multidimensional array.
// Sample multidimensional array
$users = [
['name' => 'John', 'age' => 30],
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 35]
];
// Custom comparison function to sort by age
usort($users, function($a, $b) {
return $a['age'] <=> $b['age'];
});
// Output sorted array
print_r($users);