-1

I am doing an rsort for the following array.

$list_array = array("a1"=>$a1,"a2"=>$a2,"a3"=>$a3,"a4"=>$a4,"a5"=>$a5,"a6"=>$a6,"a7"=>$a7,"a8"=>$a8,"a9"=>$a9,"a10"=>$a10,"a11"=>$a11,"a12"=>$a12,"a13"=>$a13,"a14"=>$a14,"a15"=>$a15,"a16"=>$a16, "a17"=>$a17,"a18"=>$a18,"a19"=>$a19,"a20"=>$a20,"a21"=>$a21);

rsort( $list_array, SORT_NUMERIC );

print_r( $list_array );

Result

Array ( [0] => 32.87 [1] => 8.48 [2] => 8.34 [3] => 8.33 [4] => 7.85 [5] => 5.77 [6] => 3.75 [7] => 2.42 [8] => 1.24 [9] => 0.47 [10] => 0.09 [11] => 0.06 [12] => 0.01 [13] => 0.01 [14] => 0.01 [15] => 0.01 [16] => 0.01 [17] => 0 [18] => 0 [19] => 0 [20] => 0 )

The keys are missing.

How do I fix this to keep the keys in the output?

JAAulde
  • 19,250
  • 5
  • 52
  • 63
Cody Raspien
  • 1,753
  • 5
  • 26
  • 51

1 Answers1

2

You need to use arsort instead of rsort.

Sort an array in reverse order and maintain index association

JAAulde
  • 19,250
  • 5
  • 52
  • 63
  • If I use arsort, how do I print the first 3 items without knowing the title order? – Cody Raspien Aug 29 '20 at 22:24
  • You could do a few things, depending on the needs of your code--slicing, foreach with a counter, etc. But that's an entirely different question than the one you asked. – JAAulde Aug 29 '20 at 22:27