Can you provide an example code snippet demonstrating how to use the usort() function in PHP for sorting arrays with multiple criteria?
When sorting arrays with multiple criteria in PHP, the usort() function can be used along with a custom comparison function. This comparison function should compare the elements based on the desired criteria and return -1, 0, or 1 depending on the comparison result. By using usort() with a custom comparison function, you can sort arrays based on multiple criteria efficiently.
// Example code snippet demonstrating the use of usort() for sorting arrays with multiple criteria
// Sample array with multiple elements
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35]
];
// Custom comparison function for sorting by age and then by name
usort($users, function($a, $b) {
if ($a['age'] == $b['age']) {
return strcmp($a['name'], $b['name']); // Sort by name if age is equal
}
return $a['age'] - $b['age']; // Sort by age
});
// Output sorted array
print_r($users);