2

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 able to do this?

I tried ksort but it not work as per my requirement

ksort result

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

2 Answers2

3

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
)
David Lopez
  • 1,777
  • 1
  • 8
  • 7
1

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 ) 
Rohit Kumar
  • 1,861
  • 1
  • 8
  • 16