Powered by Squarespace

Fork me on GitHub

Peter Cowburn has posted a better function of this on his blog. I have placed a snippet below of his function edited for the support of PHP 4

This function finds the mode of a number set. Currently returns FALSE if there is a tie but I would like to find the best way to return all the modes if there are multiple. Thinking of an array. Anywho, for the time being, if you'd like to find the mode of a number set and don't expect ties, copy and paste it for your pleasure.

function getMode($set) {	
if(is_array($set))
{
	$fl_s = array_values($set);
	$fnl_a = array();
	for($i = 0; $i < count($fl_s); $i++) {
	if(intval($fl_s[$i]) != 0 || $fl_s[$i] == "0") {
		if(isset($fnl_a[$fl_s[$i]]))
		{ $fnl_a[$fl_s[$i]] = $fnl_a[$fl_s[$i]] + 1;}
		else
		{ $fnl_a[$fl_s[$i]] = 1;}	
	}
	}
	if(arsort($fnl_a))
	{
		reset($fnl_a);
		$ans = key($fnl_a);
		next($fnl_a);
		if($fnl_a[$ans] == current($fnl_a))
		{return FALSE;}
		else
		{return $ans;}
	}
}
else { die ("getMode.Error = Input was not an array."); }
}

//Sample Input
$arrayIn = array(0, 0, 0, 1, 1);

//Call Function
if(getMode($arrayIn) === FALSE) { echo "TIE"; }
else { echo getMode($arrayIn); }

PHP 4 Version of Peter Cowburn's function:

/**
 * Returns the mode value(s) for an array.
 *
 * @param array The array of values to determine the mode.
 * @return mixed Return mode value if there is only one, array of values if bimodel or FALSE if no mode or not an array.
 */
function array_mode($set)
{
  if(is_array($set)) {
    $counts = array_count_values($set);
    $modes  = array_keys($counts, current($counts));
    // If each value only occurs once, there is no mode
    if (count($set) === count($counts))
        return FALSE;
 
    // Only one modal value
    if (count($modes) === 1)
      return $modes[0];
 
    // Multiple modal values
    return $modes;
  }
  else
  {
    return FALSE;
  }
}