PHP array sorting by value and index association support

I have an array:

$array = array(
    'john' => 2,
    'adam' => 3,
    'ben' => 10,
    'tim' => 1
);

      

I've tried all sorts of functions with PHP to achieve this array structure:

$array = array(
    'tim' => 1,
    'john' => 2,
    'adam' => 3,
    'ben' => 10
);

      

Where its ordered by array values ​​and stored key / values. Any ideas?

+3


source to share


2 answers


This should work with 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 a demo .

+8


source


you may be looking for asort () - sort the array and maintain index association .



0


source







All Articles