Sort array in PHP by value and maintain index association

This should work using asort():

<?php
$array = array(
    'john' => 2,
    'adam' => 3,
    'ben' => 10,
    'tim' => 1,
);
asort($array, SORT_NUMERIC);
print_r($array);
?>

output:

Array
(
    [tim] => 1
    [john] => 2
    [adam] => 3
    [ben] => 10
)

Checkout the demo.

Leave a Comment