Sunday 18 October 2020

Write a PHP script to sort the elements in descending order of an array.

 Example 1

<?php 

$numbers = array(20, 91, 4, 39, 23); 

rsort($numbers); 

$arraylength = count($numbers); 

for($x = 0; $x < $arraylength; $x++) { 

    echo $numbers[$x]; 

    echo "<br>"; 

?> 

Output: 

91

39        

23        

20        

4

Example 2

<?php

$cars = array("Maruthi", "TATA", "KIA");

rsort($cars);

$carslength = count($cars);

for($i = 0; $i < $carslength; $i++) {

  echo $cars[$i];

  echo "<br>";

}

?>

Output: 

TATA
Maruthi
KIA

Example 3

<?php

// Define array

$numbers = array(1,2,3,4,5,6,7,8,9,10);

// Sorting and printing array

rsort($numbers); // rsort- sort arrays in descending order

print_r($numbers);

?>

Output: 

Array ( [0] => 10 [1] => 9 [2] => 8 [3] => 7 [4] => 6 [5] => 5 [6] => 4 [7] => 3 [8] => 2 [9] => 1 )

Example 4

<?php

$colors = array("Red", "Blue", "Green","Yellow");

rsort($colors);

print_r($colors);

?>

Output: Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )



No comments:

Post a Comment