How to organize an array by size automatically?

Asked

Viewed 396 times

1

I was looking to create a ranking system. For this I thought to put all the values within one Array and then through a function arrange it from the largest to the smallest. However, each time I make each position, I always have to make a larger code (and I don’t know how many records they will have). The code would be similar to 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 as I will never know how many records I will keep doing this for several other records.

Is there any way to do it more dynamically?

For those who still don’t understand, I want an array x=(1,4,3,2,5,6,9,8,7,0) become an array y=(9,8,7,6,5,4,3,2,1,0)

  • 1

    function sort

1 answer

1


There is a function that reverses the 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 you.

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 to say:

  • If you want to order use sort

  • If you want to reverse use rsort

  • the problem is not to invert the array, but to sort it in the correct sequence

  • Add more details, the Sort command sorts the array

  • man, that’s exactly what I needed, thank you very much!

  • nothing we need so much. :)

  • if you can mark as right and give upvote :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.