Current Location: Home> Latest Articles> Practical Techniques for Sorting Multidimensional Arrays in PHP: In-depth Explanation and Examples

Practical Techniques for Sorting Multidimensional Arrays in PHP: In-depth Explanation and Examples

M66 2025-07-23

Practical Techniques for Sorting Multidimensional Arrays in PHP

Sorting multidimensional arrays is a common task in PHP development. Mastering proper sorting methods can significantly improve data handling efficiency and code readability.

Example Data Structure

Assume we have an array containing student names and their scores. We want to sort it primarily by name in ascending order and then by score in descending order.

$students = [
    ['name' => 'Alice', 'score' => 90],
    ['name' => 'Bob', 'score' => 85],
    ['name' => 'Charlie', 'score' => 95],
    ['name' => 'Dave', 'score' => 80],
];

Sorting with a Custom Comparison Function

By defining a comparison function, you can precisely control the sorting rules. The following function first compares names, and if the names are the same, it compares scores:

function compare_students($a, $b) {
    if ($a['name'] == $b['name']) {
        return $b['score'] <=> $a['score']; // Score descending
    }
    return strcmp($a['name'], $b['name']); // Name ascending
}

Use the usort() function to perform the sorting:

usort($students, 'compare_students');

Anonymous Function Syntax for PHP 7.4 and Above

PHP 7.4 introduced simplified anonymous functions, making the code more concise:

uasort($students, function($a, $b) {
    if ($a['name'] == $b['name']) {
        return $b['score'] <=> $a['score'];
    }
    return strcmp($a['name'], $b['name']);
});

Explanation of Sorting Principles

The comparison function accepts two array elements as parameters and returns an integer indicating their order relationship. Here, strcmp() sorts names in ascending order, and if the names are identical, the spaceship operator <=> sorts scores in descending order.

Output Example

After sorting, the output looks like this:

print_r($students);

The array is sorted alphabetically by name, and if names are the same, scores are sorted from highest to lowest.

Conclusion

Understanding the core concepts and methods for sorting multidimensional arrays in PHP helps developers handle complex sorting tasks with flexibility. Using custom comparison functions alongside PHP’s built-in sorting functions leads to clean and efficient code.