What are some common PHP array sorting functions that can be used for sorting arrays with multiple criteria?
When sorting arrays with multiple criteria in PHP, you can use functions like `array_multisort()`, `usort()`, or `uasort()` to sort the array based on different criteria. These functions allow you to define custom comparison functions to sort the array elements according to your specific requirements.
// Example of sorting an array with multiple criteria using usort()
$data = [
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Alice', 'age' => 35]
];
usort($data, function($a, $b) {
if ($a['age'] == $b['age']) {
return $a['name'] <=> $b['name'];
}
return $a['age'] <=> $b['age'];
});
print_r($data);
Related Questions
- What are some common pitfalls when using PHP to fill a table with data from a form?
- What is the best way to store and retrieve values in PHP scripts called sequentially?
- What are the alternative methods to mysql_real_escape_string in PHP for preventing SQL injection and handling special characters in text fields?