How to find the mode of an array in PHP

后端 未结 3 1927
清酒与你
清酒与你 2020-12-07 02:56

I have an array that has been sorted from low to high which has over 260k values in. I have found out the mean(average) and median of the array just need to find out the mod

相关标签:
3条回答
  • 2020-12-07 03:07

    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 />';
    }
    
    0 讨论(0)
  • 2020-12-07 03:15

    Mathematical only solution:

        //sample data
    $dataArr = ["1", "3", "5", "1", "3", "7", "1", "8", "1"];
    
    //a multidimensional array to hold the keys (extracted fro above) and their values (number of occurrences)
    $multiDArr = [];
    for ($i = 0; $i < count($dataArr); $i++) {
        $key = $dataArr[$i];
    
        if (isset($multiDArr[$key])) {
            //key already exists; increment count of its value
            $multiDArr[$key] = $multiDArr[$key] + 1;
        } else {
            //key does nto exist; add it and an inital value of 1
            $multiDArr[$key] = 1;
        }
    }
    
    $highestOccuring = 0;
    $highestOccuringKey = null;
    foreach ($multiDArr as $key => $value) {
    
        if ($value > $highestOccuring) {
            $highestOccuring = $value;
            $highestOccuringKey = $key;
        }
    
    }
    
    echo "MODE / highest occuring key: " . $highestOccuringKey;
    
    0 讨论(0)
  • 2020-12-07 03:22

    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);
    
    0 讨论(0)
提交回复
热议问题