Sort array by numeric keys
Asked Answered
E

4

13

How can I sort this array by array keys?

array(
4 => 'four',
3 => 'three',
2 => 'two',
1 => 'one',
)

Desired result:

array(
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
)
Ekg answered 11/1, 2010 at 22:27 Comment(1)
Dictionaries are not sorted ... extract the keys into a separate list and sort that.Decorous
E
27

If you just want to reverse the order, use array_reverse:

$reverse = array_reverse($array, true);

The second parameter is for preserving the keys.

Endoparasite answered 11/1, 2010 at 22:33 Comment(0)
U
36

If you want to sort the keys in DESC order use:

krsort($arr);

If you want to sort the values in DESC order and maintain index association use:

arsort($arr);

If you want to sort the values in DESC natural order and maintain index association use:

natcasesort($arr);
$arr = array_reverse($arr, true);
Untie answered 11/1, 2010 at 22:35 Comment(0)
E
27

If you just want to reverse the order, use array_reverse:

$reverse = array_reverse($array, true);

The second parameter is for preserving the keys.

Endoparasite answered 11/1, 2010 at 22:33 Comment(0)
G
3

You have an array, you want to sort it by keys, in reverse order -- you can use the krsort function :

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.


In you case, you'd have this kind of code :

$arr = array(
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
);

krsort($arr);
var_dump($arr);

which would get you this kind of output :

$ /usr/local/php-5.3/bin/php temp.php
array(4) {
  [4]=>
  string(4) "four"
  [3]=>
  string(5) "three"
  [2]=>
  string(3) "two"
  [1]=>
  string(3) "one"
}


As a sidenode : if you had wanted to sort by values, you could have used arsort -- but it doesn't seem to be what you want, here.

Gupta answered 11/1, 2010 at 22:31 Comment(0)
M
0

Try krsort() - that will sort in reverse using the array key, whereas rsort will sort on the array value.

Margoriemargot answered 11/1, 2010 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.