3

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
)
4
  • Use ksort Commented Oct 1, 2015 at 7:03
  • Possible duplicate of Reference: all basic ways to sort arrays and data in PHP Commented Oct 1, 2015 at 7:03
  • 1
    If all the keys were strings like the key '11' ksort (with SORT_STRING flag) will work as you wanted. Commented Oct 1, 2015 at 7:10
  • @DavidLopez you should add answer :) you are right. Commented Oct 1, 2015 at 7:16

2 Answers 2

4

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
)
Sign up to request clarification or add additional context in comments.

Comments

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 ) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.