How can arrays be sorted in PHP based on multiple criteria?
To sort arrays in PHP based on multiple criteria, you can use the `usort()` function along with a custom comparison function. This function will compare the elements of the array based on the multiple criteria you define. By implementing a custom comparison function, you can specify the logic for sorting the array based on different criteria.
// Sample array to be sorted based on multiple criteria
$students = array(
array('name' => 'Alice', 'age' => 20),
array('name' => 'Bob', 'age' => 25),
array('name' => 'Charlie', 'age' => 22)
);
// Custom comparison function to sort based on name and then age
usort($students, function($a, $b) {
if ($a['name'] == $b['name']) {
return $a['age'] - $b['age'];
}
return strcmp($a['name'], $b['name']);
});
// Print the sorted array
print_r($students);