Question

I have an array of tags which contains keys and as value the number of occurences in a previous array:

Array ( [789] => 1 [sss] => 2 [aaa] => 3 [bbb] => 1 [taf] => 1 )

Now I would like to sort this array by number of occurence I do this by using the following command:

array_multisort($array, SORT_DESC);

It works, but it changes the value of key "789" to 0 for some reason, so I get the following output:

Array ( [aaa] => 3 [sss] => 2 [taf] => 1 [0] => 1 [bbb] => 1 ) 

The values are retrieved from the database, when I change 789 to 789-, it works correctly. So I assume the sorting goes wrong because 789 is a number. Is there a way to achieve the desired result? I tried converting 789 to a string but without result.

Was it helpful?

Solution

There is a function especially for this purpose (ironically) that preserves the keys while sorting in descending order, it's called arsort();

arsort($array);

Output

Array
(
    [aaa] => 3
    [sss] => 2
    [taf] => 1
    [789] => 1
    [bbb] => 1
)

DEMO

The problem with array_multisort() as it states in the documentation:

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top