Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get three highest values from the array

I want to get three highes values from my array, but it should be sorted properly by keys also.

I have this code:

<?php
$a = array(130, 1805, 1337);
arsort($a);
print_r($a);
?>

The output of the above is following:

Array
(
    [1] => 1805
    [2] => 1337
    [0] => 130
)

Its working fine, but I want it additionaly to sort its keys from the highest to the lowest value.

Example:

Array
(
    [2] => 1805
    [1] => 1337
    [0] => 130
)

To be clear: I want it be to sorted by the keys: array key number 2 will be always used for the highest value, array key number 0 will be always used for the lowest value.

How can I do that?

/let me know if you don't understand something.

like image 262
Cyclone Avatar asked Dec 27 '22 03:12

Cyclone


1 Answers

rsort($array);
$top3 = array_reverse(array_slice($array, 0, 3));
like image 137
deceze Avatar answered Jan 08 '23 18:01

deceze