phparrayssorting

Sort keys of an array


I have this array:

$arr = array('Stone', 'Gem', 'Star', ..., 'Star', 'Rock', 'Salt', ..., 'Metal', 'Cotton', 'Gem',...);
$array = array_count_values($arr);

So the output is like this:

Array
(
    [Stone] => 234
    [Gem] => 231
    [Star] => 123
    [Rock] => 232
)

Now I am trying to sort it alphabetically like,

[Gem] => ...
[Star] => ...
[Stone] => ...
[Rock] => ...

I tried this one:

sort($arr);
foreach($arr as $key => $value){
    echo $key.' : '.$value;
}

But the output is not what I have expected it look like this:

0 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 110 : 11 ...

Any ideas how I can correctly sort this?


Solution

  • Have you tried ksort() ?

    ksort($arr)
    
    print($arr)
    

    You can get the doc over here.