2

Please how do I sort the below array

Array
(
    'ben' => 1.0,
    'ken' => 2.0,
    'sam' => 1.5
)

to

Array
(
    'ken' => 2.0,
    'sam' => 1.5,
    'ben' => 1.0
)
1
  • why you have used ' near numbers like 'ben' => 1.0',. Commented Jul 14, 2011 at 4:14

6 Answers 6

3

try this.

<?php
$my_array = array('ben' => 1.0, 'ken' => 2.0, 'sam' => 1.5);

arsort($my_array);
print_r($my_array);
?>

The arsort() function sorts an array by the values in reverse order. The values keep their original keys.

0
2

http://www.php.net/manual/en/function.rsort.php

2

There's a whole manual section dedicated to such things:

http://php.net/manual/en/array.sorting.php

edit: specifically, arsort()

1
$arr = Array(
'ben' => 1.0,
'ken' => 2.0,
'sam' => 1.5
)    
$sorted = asort($arr);
$reversed = rsort($sorted);
3
  • Thanks. But the array keys where not retained Commented Jul 14, 2011 at 4:15
  • That's strange. According to the documentation, asort maintains the keys. Oh, I see, rsort is mixing it up again. hmmmm Commented Jul 14, 2011 at 4:19
  • Yes, rsort is the bad guy there. asort() works but i still had to use array_reverse() to get a DESC order. Thanks anyway. Commented Jul 14, 2011 at 4:29
1

If you use regular PHP array sorting functions, you'll lose your array keys. I think the shortest path to what you want is something like this:

$array = array("ben" => "1.0", "ken" => "2.0", "sam" => "1.5");
array_multisort($array, SORT_DESC);
print_r($array);

Make sure that all of your array values are either strings or numbers, otherwise the result will be unpredictable.

0
0

The sort function should work:

sort($theArray, SORT_NUMERIC);

Update

I didn't notice you wanted it in reverse; in that case use rsort.

2
  • This sorts low to high. Poster wants high to low. Thus rsort(); Commented Jul 14, 2011 at 3:59
  • Yeah just saw that... i need to pay more attention :-) Gave you both +1 Commented Jul 14, 2011 at 4:00

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.