0

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?

1
  • @Elias given that Stack Overflow has literally hundreds of php sorting question, please be more selective to nominate a duplicate page which closely resembles the task. This question seeks sorting on the keys of a flat, associative array and your nomination demonstrates how to sort a 2d array by a column value. This is not helpful for researchers or Stack Overflow content curation. Commented Feb 1 at 5:14

2 Answers 2

4

Have you tried ksort() ?

ksort($arr)

print($arr)

You can get the doc over here.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.