Skip to content
PHP Logo

What are the best practices for sorting data in PHP when dealing with multiple sorting criteria?

When dealing with multiple sorting criteria in PHP, it is best to use the `usort()` function along with a custom comparison function. This allows you to define the logic for sorting based on multiple criteria. You can create a comparison function that compares the values according to each criterion in order of priority.

php
// Example of sorting an array of data based on multiple criteria
$data = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 35],
];

usort($data, function($a, $b) {
    if ($a['age'] == $b['age']) {
        return $a['name'] <=> $b['name']; // Sort by name if age is equal
    }
    return $a['age'] <=> $b['age']; // Otherwise, sort by age
});

print_r($data);