If you’ve ever needed to get calculate a mode value in php, you’ll notice that there isn’t a native function to do so.
I couldn’t get the function in Pear’s Math_Statistics to work with non-numeric values, so here’s a function that does.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php /** * Calculates the frequently occuring value(s) in an array. * * @param array $data * @return array */ function array_mode($data) { if(!is_array($data)) { throw new Exception('First argument $data must be an array.'); } $frequencies = array_count_values($data); // Double-check that frequencies are sorted in reverse order, // I think array_count_values actually returns in this format // already, but the manual doesn't mention it. arsort($frequencies); $isFirst = true; // Yuk $mode = array(); foreach ($frequencies as $thisValue=>$thisFrequency) { if ($isFirst == true) { $isFirst = false; // Wince $mode[] = $thisValue; $modeFrequency = $thisFrequency; continue; } if ($modeFrequency == $thisFrequency) { $mode[] = $thisValue; } if ($modeFrequency > $thisFrequency) { break; } } return $mode; } var_dump(array_mode(array('a', 'a', 'b', 'c', 'd'))); /* array(1) { [0]=> string(1) "a" } */ var_dump(array_mode(array('a', 'a', 'b', 'b', 'c'))); /* array(2) { [0]=> string(1) "a" [1]=> string(1) "b" } */ |
Published at 10:49 am on May 3rd, 2007.
Topics: PHP