PHP Program to Sort an Array Elements in Descending Order
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);
?>
Output
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);
?>
Output
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);
?>
Output
Array ( [0] => 8 [1] => 5 [2] => 3 [3] => 2 [4] => 1 )
Using array_multisort()
array_multisort() sorts arrays and can handle multiple arrays simultaneously. To sort a single array in descending order
Example:
<?php
$array = [5, 2, 9, 1, 5, 6];
array_multisort($array, SORT_DESC);
print_r($array);
// Output will be visible in the console
?>
Output
Array ( [0] => 9 [1] => 6 [2] => 5 [3] => 5 [4] => 2 [5] => 1 )
Using arsort() Function
The arsort() function is another built-in PHP function specifically designed for sorting an associative array in descending order according to its values while maintaining key association.
Example:
<?php
$arr = [5, 2, 8, 1, 3];
// Sort the array in descending order
arsort($arr);
// Display the sorted array
print_r($arr);
?>
de
?>
Output
Array ( [2] => 8 [0] => 5 [4] => 3 [1] => 2 [3] => 1 ) de ?>
Using uksort() Function
The uksort() function sorts an associative array by keys using a user-defined comparison function, allowing customization for descending order sorting based on keys.
Example:
<?php
// Example associative array
$array = ['c' => 3, 'a' => 1, 'b' => 2];
// Sort array by keys in descending order using uksort()
uksort($array, function($a, $b) {
return strcmp($b, $a);
});
print_r($array); // Output: ['c' => 3, 'b' => 2, 'a' => 1]
?>
Output
Array ( [c] => 3 [b] => 2 [a] => 1 )