5

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.

1
  • Did any of the answers here correctly sorted by value and key? Commented Mar 30, 2012 at 21:07

6 Answers 6

8
rsort($array);
$top3 = array_reverse(array_slice($array, 0, 3));
Sign up to request clarification or add additional context in comments.

5 Comments

Just a note for @Cyclone, if you use array_slice as @deceze pointed out, it will only return the top 3 values. If you want to affect all values, leave it out.
@deceze Thank you ! :-) That was what I've looking for.
@deceze I wouldn't hold your breath, it's was probably more of an 'elevation through collateral downvoting' strategy... So sad
Why not $top3 = array_slice($array, -3);?
@Alix True, that's a nice solution as well when combined with sorting the other way.
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[0], $a[1], $[2] to get your highest values.

Comments

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

Would produce:

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

You can find out more about it here.

1 Comment

Just a note: array_reverse() doesn't change the original array, it returns the reversed array, so you have to catch it in a variable or it's useless.
0

I would try:

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

Comments

0

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
(
    [2] => 1805
    [1] => 1337
    [0] => 130
)

Comments

0
<?php 

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

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

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.