array_mode

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.

<?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"
}
*/

Comments