PHP: Sorting an array with numerical reduction

this question looks like it should have a simple answer, but google and the php manual don't help me, maybe I just don't understand what they are telling me.

I have an array example:

$outcomes_array = array(1,4,2,3,5); 

It will always contain only numbers, how can I sort this array so that it is always in descending order?

so the conclusion i want is:

 $outcomes_array[0] = 5 $outcomes_array[1] = 4 $outcomes_array[2] = 3 

etc.

Thanks:)

+6
source share
6 answers

Use rsort() .

+14
source
 rsort( $outcomes_array ) 

Please note that this is not

 $outcomes_array = rsort( $outcomes_array ); 
+6
source
 rsort( $outcomes_array ); print_r( $outcomes_array ); 
+4
source
  • rsort for numeric array only
  • arsort for an array with keys
+2
source

By default, SORT_REGULAR - usually compares elements (do not change types). Thus, the code should be:

 $outcomes_array = array(1,4,2,3,5); rsort( $outcomes_array, SORT_NUMERIC );//SORT_NUMERIC - compare items numerically print_r( $outcomes_array ); 
0
source
 $array = [2, 1, 22, 1, 3, 134, 3, 43, 23, 4]; function mi($arr){ $count = count($arr); for ($j = 0; $j < $count; $j++) { $min = $arr[0]; for ($i = 0; $i < count($arr); $i++) { if ($arr[$i] <= $min) { $min = $arr[$i]; } } $ar[] = $min; for ($i = 0; $i < count($arr); $i++) { if ($arr[$i] == $min) { unset ($arr[$i]); $arr = array_values($arr); break; } } } return $ar; } print_r(mi($array)); 
0
source

Source: https://habr.com/ru/post/889122/


All Articles