6

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?

1

2 Answers 2

12

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.

1
  • 2
    Can you show me the output please because I am getting different results! Mar 27, 2012 at 22:58
-1

perhaps you are looking for asort() — Sort an array and maintain index association.

1
  • 1
    Please provide some detail in you answer rather than just a link.
    – PeeHaa
    Mar 27, 2012 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.