MathPHP\Statistics\Average::mode PHP Method

mode() public static method

Always returns an array, even if only one mode.
public static mode ( array $numbers ) : array
$numbers array
return array of mode(s)
    public static function mode(array $numbers) : array
    {
        if (empty($numbers)) {
            return [];
        }
        // Count how many times each number occurs
        // Determine the max any number occurs
        // Find all numbers that occur max times
        $number_counts = array_count_values($numbers);
        $max = max($number_counts);
        $modes = array();
        foreach ($number_counts as $number => $count) {
            if ($count === $max) {
                $modes[] = $number;
            }
        }
        return $modes;
    }

Usage Example

Example #1
0
 /**
  * Get a report of all the descriptive statistics over a list of numbers
  * Includes mean, median, mode, range, midrange, variance, standard deviation, quartiles, etc.
  *
  * @param array $numbers
  * @param bool  $population: true means all possible observations of the system are present;
  *              false means a sample is used.
  * @return array [ n, mean, median, mode, range, midrange, variance, sd, CV, mean_mad,
  *                 median_mad, quartiles, skewness, kurtosis, sem, ci_95, ci_99 ]
  */
 public static function describe(array $numbers, bool $population = false) : array
 {
     $n = count($numbers);
     $μ = Average::mean($numbers);
     $σ = self::standardDeviation($numbers, $population);
     return ['n' => $n, 'min' => min($numbers), 'max' => max($numbers), 'mean' => $μ, 'median' => Average::median($numbers), 'mode' => Average::mode($numbers), 'range' => self::range($numbers), 'midrange' => self::midrange($numbers), 'variance' => $population ? self::populationVariance($numbers) : self::sampleVariance($numbers), 'sd' => $σ, 'cv' => $σ / $μ, 'mean_mad' => self::meanAbsoluteDeviation($numbers), 'median_mad' => self::medianAbsoluteDeviation($numbers), 'quartiles' => self::quartiles($numbers), 'midhinge' => self::midhinge($numbers), 'skewness' => $population ? RandomVariable::populationSkewness($numbers) : RandomVariable::skewness($numbers), 'ses' => RandomVariable::SES($n), 'kurtosis' => RandomVariable::kurtosis($numbers), 'sek' => RandomVariable::SEK($n), 'sem' => RandomVariable::standardErrorOfTheMean($numbers), 'ci_95' => RandomVariable::confidenceInterval($μ, $n, $σ, 95), 'ci_99' => RandomVariable::confidenceInterval($μ, $n, $σ, 99)];
 }