How to organize an array by size automatically?

1

I was looking to create a ranking system. For this I thought of putting all the values inside a Array and then through a function to organize it from the largest to the smallest. However, every time I do each position, I always have to make a larger code (and I do not know how many records will be). The code would look like this:

<?php
  // essa função recebe um array como parâmetro
  function ordenaArray($array){
     $arrayOrdenado = array();
     $indice = 0;
     $maior = 0;
     for($i = 0; $i <= count($array); $i++){
       if($array[$i] >= $maior){
           $maior = $array[$i];
       }
     }
   $arrayOrdenado[$indice] = $maior;
   $indice++;
  }
?>

I can do this for all records, but since I'll never know how many records they'll have, I'll keep doing this for several other records.

Do you have any way to do this more dynamically?

  

For those who still do not understand, I want an array x=(1,4,3,2,5,6,9,8,7,0) to turn an array y=(9,8,7,6,5,4,3,2,1,0)

    
asked by anonymous 13.10.2017 / 18:32

1 answer

1

There is a function that inverts array in PHP, which is called array_reverse :

<?php
$input  = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>

From what I understand, she answers.

If you need to sort first use this way:

<?php
 $array = array('d', '1', 'b', '3', 'a', '0', 'c', '2');

 sort($array); // Classifica o Array em ordem Crescente.

 print_r($array); // Resultado: Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => a [5] => b [6] => c [7] => d )

 echo '<br/>';

 rsort($array); // Classifica o Array em ordem Decrescente.

 print_r($array); // Resultado: Array ( [0] => d [1] => c [2] => b [3] => a [4] => 3 [5] => 2 [6] => 1 [7] => 0 )
?>

The command sort() will do the job.

That is:

  • If you want to sort use sort

  • If you want to invert use rsort

13.10.2017 / 18:33