Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array in PHP by value and maintain index association

Tags:

arrays

php

I have an array:

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

I have 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 the array values and the key/values maintained. Any ideas?

like image 614
benhowdle89 Avatar asked Mar 27 '12 22:03

benhowdle89


1 Answers

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.

like image 192
stewe Avatar answered Oct 01 '22 20:10

stewe