Avinash
Avinash

Reputation: 91

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
)

Upvotes: 3

Views: 92

Answers (2)

Rohit Kumar
Rohit Kumar

Reputation: 1958

You can achive this by using uksort to get desired result .The uksort() function sorts an array by keys using a user-defined comparison function.

$a= array(    0=>'test', 1=>'test1', 10=>'test10',
               2=>'test2', '11'=>'test11',22=>'test22'
         );
function my_sort($a,$b)
{
if ($a==0) return 0;
return (substr($a, 0, 1)<substr($b, 0, 1))?-1:1;
}

uksort($a,"my_sort");
print_r($a);

Output

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

Upvotes: 1

David Lopez
David Lopez

Reputation: 2247

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
)

Upvotes: 4

Related Questions