Search code examples
phparrayssortingksort

Sort array by numeric keys


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',
)

Solution

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

    $reverse = array_reverse($array, true);
    

    The second parameter is for preserving the keys.