gibigbig Posted January 11, 2011 Share Posted January 11, 2011 I have an array and I'd like to find the most popular value in the array. example. $arr = array(1,1,1,1,2,2,3,4,5,5,5,5,5,5,5,3,4,198,10293,1,2); I would like only display 5 please. Quote Link to comment Share on other sites More sharing options...
punk_runner Posted January 11, 2011 Share Posted January 11, 2011 <?php # returns most common value in input array function array_most_common($input) { $counted = array_count_values($input); arsort($counted); return(key($counted)); } Quote Link to comment Share on other sites More sharing options...
gibigbig Posted January 11, 2011 Author Share Posted January 11, 2011 not working with my code Warning: array_count_values() [function.array-count-values]: Can only count STRING and INTEGER values! in [path]/downloads2.php on line 270 Let me explain a bit more, I have a table in the database named posts. A field in the posts is named "added_by_userid" and I would like to get the "added_by_userid" with the most records in that table. Maybe this can be done with SQL? Quote Link to comment Share on other sites More sharing options...
gibigbig Posted January 11, 2011 Author Share Posted January 11, 2011 ok nevermind, I found my error, thank you so much, your code works great. Quote Link to comment Share on other sites More sharing options...
punk_runner Posted January 11, 2011 Share Posted January 11, 2011 Yeah, you wouldn't want to build a huge array with every post ID... that sucks resources. Try this: (I didn't run this so excuse any typos, but it is close)... $result = mysql_query("SELECT added_by_userid, COUNT(added_by_userid) AS userid FROM posts GROUP BY added_by_userid ORDER BY userid DESC LIMIT 1"); $row = mysql_fetch_assoc($result); echo "<p>The most popular userid listed is " . row['added_by_userid'] . "</p>"; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.