Search code examples
phparrayssortinglexicographic

Sort array by numeric keys as if they were strings


I have one array

$a = array(
    0 => 'test',
    1 => 'test some',
    10 => 'test10',
    2 => 'test2',
    '11' => 'test value',
    22 => 'test abc'
);

I need to sort it like

0 => test
1 => test some
10 => test 10
11 => test value
2 => test2
22 => test abc

How can I do this?

I tried ksort(), but it does not work as per my requirement.

ksort() result

Array
(
    [0] => test
    [1] => test1
    [2] => test2
    [10] => test10
    [11] => test11
    [22] => test22
)

Solution

  • This should work:

    $a = array(0=>'test', 1=>'test1', 10=>'test10', 2=>'test2', '11'=>'test11', 22=>'test22');
    ksort($a, SORT_STRING);
    print_r($a)
    

    Output:

    Array
    (
        [0] => test
        [1] => test1
        [10] => test10
        [11] => test11
        [2] => test2
        [22] => test22
    )