How to find the mode of an array in PHP

后端 未结 3 1946
清酒与你
清酒与你 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: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;
    

提交回复
热议问题