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
)
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.
There's a whole manual section dedicated to such things:
http://php.net/manual/en/array.sorting.php
edit: specifically, arsort()
$arr = Array(
'ben' => 1.0,
'ken' => 2.0,
'sam' => 1.5
)
$sorted = asort($arr);
$reversed = rsort($sorted);
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.
The sort
function should work:
sort($theArray, SORT_NUMERIC);
I didn't notice you wanted it in reverse; in that case use rsort
.
'
near numbers like'ben' => 1.0',
.