PHP Program to Sort an Array Elements in Descending Order
Last Updated :
17 Jan, 2024
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.
Using rsort() Function
The rsort()
function is a built-in PHP function specifically designed for sorting an array in descending order.
PHP
<?php
$arr = [5, 2, 8, 1, 3];
rsort( $arr );
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
<?php
$arr = [5, 2, 8, 1, 3];
sort( $arr );
$arr = array_reverse ( $arr );
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
<?php
$arr = [5, 2, 8, 1, 3];
usort( $arr , function ( $a , $b ) {
return $b - $a ;
});
print_r( $arr );
?>
|
Output
Array
(
[0] => 8
[1] => 5
[2] => 3
[3] => 2
[4] => 1
)
Share your thoughts in the comments
Please Login to comment...