phparrayssortingassociative-array

Sort a flat array by values in a descending direction and preserve the keys


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
)

Solution

  • 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.