How to find the mode of an array in PHP

烂漫一生 提交于 2019-11-28 02:04:35

The mode of a numerical set is the number that occurs the most often. You can do this with PHP using code similar to the following:

$values = array_count_values($valueArray); 
$mode = array_search(max($values), $values);

Simple!

$arr = array(4,6,7,1,4,7,4,7,1);
$freq = array();
for($i=0; $i<count($arr); $i++)
{
   if(isset($freq[$arr[$i]])==false)
   {
       $freq[$arr[$i]] = 1;
   }
   else
   {
       $freq[$arr[$i]]++;
   }
}
$maxs = array_keys($freq, max($freq));

for($i=0; $i<count($maxs); $i++)
{
   echo $maxs[$i] . ' ' . $freq[$maxs[$i]];
   echo '<br />';
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!