Sort an array descending in PHP [closed]

1

Do I need to show that on the screen with a array with PHP, any suggestions?

<?php
$number= array("1","2","3","4","5","6","7","8","9","10");
arsort($number);
for($x = 0; $x < count($number); $x++) {
    echo $number[$x];
    echo "<br>";
}
?>
    
asked by adrian ruiz picazo 27.02.2018 в 18:33
source

2 answers

0

Indeed, the function that would do the best you want would be rsort .

According to the PHP Manual this feature :

  • Sort an array in reverse order (highest to lowest)

And there is another interesting thing that says:

  • This function assigns new keys to the elements of the array.

Having seen this, once the array is ordered from highest to lowest, you can work only with the array to present the data as well. Since the function assigns new keys, you can read in a foreach each key / value of the array to present the value and the order in which it has been. Since the keys start with 0 , you would have to add 1 to the key in each step of the loop.

In this way the code is cleaner, and you use less variables. You will only work with your data, so you will gain in performance.

Let's see:

▸ Code:

VIEW DEMO IN REXTESTER

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

foreach ($arrNumbers as $k=>$v){
    print ($k+1)."°- ".$v.PHP_EOL;
}

▸ Result:

1°- 10
2°- 9
3°- 8
4°- 7
5°- 6
6°- 5
7°- 4
8°- 3
9°- 2
10°- 1

Additional note:

Since apparently you will need to do this operation several times, you can create a function that does the job just by passing it in the array parameter.

The function would be more or less like this (I present it in a simple version, knowing that it could be improved, making it control for example if the value received is an array, etc):

function ordenDescendente($arrNumbers){
    rsort($arrNumbers);
    foreach ($arrNumbers as $k=>$v){
        print ($k+1)."°- ".$v.PHP_EOL;
    }    
}

And to use it with several arrays:

$arrNumbers= array("7","3","1","5");
ordenDescendente($arrNumbers);

You get:

1°- 7
2°- 5
3°- 3
4°- 1

Use with a different array:

$arrNumbers= array("9","3","7","1","5");
ordenDescendente($arrNumbers);

You get:

1°- 9
2°- 7
3°- 5
4°- 3
5°- 1

This is the type of cadidatas functions for a Utilitarian Class in any application.

I hope it serves you.

    
answered by 28.02.2018 в 05:45
0

I think the function you're looking for is called rsort ordering the values in the downward direction, arsort orders and keeps the indexes assigned

$a=array(1,2,3,4);
rsort($a);
print_r($a);

For your case you could do

$number= array("1","2","3","4","5","6","7","8","9","10");
rsort($number);
for($x = 0; $x < count($number); $x++) {
    echo ($x+1) ."°-".$number[$x];
    echo "<br>";
}
    
answered by 27.02.2018 в 21:38