gadss
gadss

Reputation: 22489

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?

Upvotes: 0

Views: 48

Answers (2)

Om Prakash
Om Prakash

Reputation: 86

Have you tried ksort() ?

ksort($arr)

print($arr)

You can get the doc over here.

Upvotes: 4

Elon Than
Elon Than

Reputation: 9765

You are sorting by keys, not values, so you should use ksort() function.

Upvotes: 0

Related Questions