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. Link to comment https://forums.phpfreaks.com/topic/224114-urgent-help-needed-with-arrays/ 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)); } Link to comment https://forums.phpfreaks.com/topic/224114-urgent-help-needed-with-arrays/#findComment-1158035 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? Link to comment https://forums.phpfreaks.com/topic/224114-urgent-help-needed-with-arrays/#findComment-1158042 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. Link to comment https://forums.phpfreaks.com/topic/224114-urgent-help-needed-with-arrays/#findComment-1158054 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>"; Link to comment https://forums.phpfreaks.com/topic/224114-urgent-help-needed-with-arrays/#findComment-1158055 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.