Sort Items In Array By Desc In PHP
Code snippet for how to Sort Items In Array By Desc In PHP with sample and detail explanation
PHP is an extensively used scripting language that makes it easier to develop dynamic and interactive Web pages on the server side. This article will introduce a simple method that allows you to sort items in an array in descending order using PHP.
Code Snippet For Sorting Items In Array By Desc
<?php
$array = array(23, 14, 56, 12, 277, 18, 39);
rsort($array);
print_r($array);
?>
Code Explanation For Sorting Items In Array By Desc
The PHP ‘rsort()’ function is vital in sorting the array elements in descending order.
Breaking it down:
-
$array = array(23, 14, 56, 12, 277, 18, 39);
: An array is declared with randomly chosen numbers. This array is the one that will be sorted in descending order. -
rsort($array);
: ‘rsort()’ is a built-in PHP function employed to sort the numeral and string arrays in descending order. This function returns True on success, and False on failure. -
print_r($array);
: The ‘print_r()’ function in PHP is utilized to print the human-readable information about a variable. Here, ‘print_r()’ is used to print the sorted array in descending order.
When the code is executed, the array values will be sorted in a descending order, meaning that the highest value will appear first and the lowest value will appear last. Consequently, the output will be:
Array
(
[0] => 277
[1] => 56
[2] => 39
[3] => 23
[4] => 18
[5] => 14
[6] => 12
)
Taking advantage of the ‘rsort()’ function can facilitate easy manipulation and utilization of data in your application. It is a quick and effective solution to sort elements in an array in descending order in PHP.