Given an array containing some elements, the task is to sort the array elements in descending order in PHP. Sorting elements of an array is a common operation in programming, and PHP provides several methods to accomplish this task.
Table of Content
Using rsort() Function
The rsort()
function is a built-in PHP function specifically designed for sorting an array in descending order.
<?php $arr = [5, 2, 8, 1, 3];
// Sort the array in descending order rsort( $arr );
// Display descending order sorted array print_r( $arr );
?> |
Array ( [0] => 8 [1] => 5 [2] => 3 [3] => 2 [4] => 1 )
Using array_reverse() with sort() Functions
Another approach is to use the combination of array_reverse() and sort() functions to achieve the descending order sorting.
<?php $arr = [5, 2, 8, 1, 3];
// Sort the array in ascending order sort( $arr );
// Reverse the array to get //descending order $arr = array_reverse ( $arr );
// Display the sorted array // (Descending order) print_r( $arr );
?> |
Array ( [0] => 8 [1] => 5 [2] => 3 [3] => 2 [4] => 1 )
Using usort() with Custom Comparison Function
The usort() function allows you to sort an array using a custom comparison function, providing more flexibility in sorting criteria.
<?php $arr = [5, 2, 8, 1, 3];
// Sort the array in descending order usort( $arr , function ( $a , $b ) {
return $b - $a ;
}); // Display the sorted array // (descending order) print_r( $arr );
?> |
Array ( [0] => 8 [1] => 5 [2] => 3 [3] => 2 [4] => 1 )