# 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
(
 => 1805
 => 1337
 => 130
)
``````

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

Example:

``````Array
(
 => 1805
 => 1337
 => 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.

## Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

### Solution 1

``````rsort(\$array);
\$top3 = array_reverse(array_slice(\$array, 0, 3));
``````

### Solution 2

You should use `array_reverse` for this.

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

Easily accessed by `\$a`, `\$a`, `\$` to get your highest values.

### Solution 3

``````\$a = array(130, 1805, 1337);
arsort(\$a);
array_reverse(\$a);
``````

Would produce:

``````Array
(
 => 1807
 => 1337
 => 130
)
``````

You can find out more about it here.

### Solution 4

I would try:

``````<?php
\$a = array(130, 1805, 1337);
arsort(\$a);
\$a = array_reverse(\$a);
``````

### Solution 5

I couldn’t get the output you described with any of the answers already posted (tested via IDEOne.com).

Here is my solution (demo):

``````\$a = array(130, 1805, 1337);

\$keys = array_keys(\$a); rsort(\$keys, SORT_NUMERIC);
\$values = array_values(\$a); rsort(\$values, SORT_NUMERIC);

\$a = array_combine(array_slice(\$keys, 0, 3), array_slice(\$values, 0, 3));

print_r(\$a);
``````

Output:

``````Array
(
 => 1805
 => 1337
 => 130
)
``````

### Solution 6

``````<?php

\$array = array(130, 1805, 1337);
sort(\$array);
for (\$i=0; \$i <= count(\$array)-1; \$i++)

\$arr[]=\$array[\$i];
print_r(\$arr);

?>
``````

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0