Multi-Key Sort
Write a PHP function that sorts a 2D array (table) by multiple columns with specified sort directions. Each sort specification is an array [columnIndex, direction] where direction is 'asc' or 'desc'.
Use usort() with an anonymous comparator function that captures the $specs array via the use keyword. Inside the comparator, iterate through each sort spec. For each spec, compare the column values of both rows.
PHP's spaceship operator <=> simplifies comparison: $a <=> $b returns -1 if $a < $b, 0 if equal, 1 if $a > $b. For descending order, swap the operands: $b <=> $a.
If all sort specs are exhausted and no difference is found between rows, return 0 to maintain relative order (stable sort behavior).
Time complexity is O(n log n). Space complexity is O(1) for in-place sorting.
Multi-column sorting is essential in data processing where records need ordering by multiple criteria. The custom comparator approach with usort() is flexible and powerful, supporting any number of sort columns with individual directions.
The spaceship operator <=> introduced in PHP 7 provides consistent comparison behavior across different types, making it the preferred approach for custom sorting comparators.Example Input & Output
Algorithm Flow

Solution Approach
Write a PHP function that sorts a 2D array (table) by multiple columns with specified sort directions. Each sort specification is an array [columnIndex, direction] where direction is 'asc' or 'desc'.
Use usort() with an anonymous comparator function that captures the $specs array via the use keyword. Inside the comparator, iterate through each sort spec. For each spec, compare the column values of both rows.
PHP's spaceship operator <=> simplifies comparison: $a <=> $b returns -1 if $a < $b, 0 if equal, 1 if $a > $b. For descending order, swap the operands: $b <=> $a.
If all sort specs are exhausted and no difference is found between rows, return 0 to maintain relative order (stable sort behavior).
Time complexity is O(n log n). Space complexity is O(1) for in-place sorting.
Best Answers
<?php
function multiSort($d, $s) {
usort($d, function($a,$b)use($s){foreach($s as [$c,$dir]){if($a[$c]!=$b[$c]){return $dir==='asc'?$a[$c]<=>$b[$c]:$b[$c]<=>$a[$c];}}return 0;});
return $d;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
