How can usort() be used to sort a multidimensional array in PHP?
To sort a multidimensional array in PHP using `usort()`, you can define a custom comparison function that compares the elements based on the criteria you want to sort by. This function should be passed as the second argument to `usort()`. Within the comparison function, you can access the specific elements of the multidimensional array that you want to compare.
// Sample multidimensional array
$students = [
['name' => 'Alice', 'age' => 20],
['name' => 'Bob', 'age' => 22],
['name' => 'Charlie', 'age' => 18]
];
// Custom comparison function to sort by age
usort($students, function($a, $b) {
return $a['age'] - $b['age'];
});
// Output sorted array
print_r($students);
Keywords
Related Questions
- How can developers optimize image handling processes in PHP to ensure compatibility with different image formats and transparency requirements?
- How can relative path references be utilized effectively in PHP scripts to avoid errors related to absolute paths?
- How can CSS properties like "overflow-y" be utilized to manage text display in a box?