Sorting an array so that the index does not move?

74 Views Asked by At

How would I sort an array, in that the values move and the index's stay still. I wrote this code below, although the answer it gave is not ideal.

$array = array(6,2,22,15,33,40,30,70,65);
asort($array,);
print_r($array);

Now this sorts the values, but the index moves with the value. I get the answer;

Array ( [1] => 2 [0] => 6 [3] => 15 [2] => 22 [6] => 30 [4] => 33 [5] => 40 [8] => 65 [7] => 70 )

Although I would like it to show as the following;

Array ( [0] => 2 [1] => 6 [2] => 15, etc.

Thank you!

1

There are 1 best solutions below

0
Gergely Lukacsy On

Use array_combine()*

It merges two arrays into one using the first as a set of keys, and the second one as set of values for the new array.

So basically you only need to get the original keys and the sorted values, and then feed them to array_combine().

$a = [
  'a' => 'orange',
  'b' => 'apple',
  'o' => 'banana',
];

$tmp = $a;
sort($tmp);
$result = array_combine(array_keys($a), $tmp);

var_dump($a, $result);

You can try it out here.

Cheers.


*:available from PHP 5.