Hi

I have an array, of several elements (which I populate from reading from a db) that may or may not have duplicate values in it.

I want to sort the array so that the value that occurs the most amount of times is top, etc, so when I output the array, it is in order of the most frequent occuring value to the least.

If there's no duplicate values then I'll want to reverse the array - and i know array_reverse() will do that.

I've seen usort() but I'm not sure if that's what I need.

Can anyone help!

Thanks.

    You could define your own function logic for the sorting

    then use uasort() and supply the function.

    uasort will preserve your associative array.

    http://www.php.net/uasort

      Use array_count_values() to see how often each value occurs then use that in the custom sort function used by uasort().

      function freq_sort($a, $b) {
      	global $k;
      	if ($k[$a] == $k[$b]) return 0;
      	return ($k[$a] > $k[$b]) ? -1 : 1;
      }
      
      $array = array(1,2,1,3,2,4,5,2,3,4,2,5,1,1,2,3,4,3,2,1,2);
      
      $k = array_count_values($array);
      uasort($array, 'freq_sort');
      
      // check results
      echo '<pre>', print_r($array, true), '</pre>';

        maybe you can use the db to populate your array sorted
        ( add "order by" to the select-statement )

          Thanks for your replies.

          I've yet to have time to try your suggestions, but thank you for repling and I will try and give them ago in the next couple of days!

          Thanks again.

            Write a Reply...