-1

I'm writing some code for an educational purpose and I need the code to calculate the mode(s) of a randomly generated array of values.

If there is only one mode (like 5 in the data set: 2, 3, 4, 5, 5, 6, 7) then this is easy (see White Elephant's answer here: How to find the mode of an array in PHP).

However I'm having trouble with instances in which there are more than one mode (like 3 and 4 in this data set: 1, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6).

The logic of how to do this already seems to be out there in Javascript (https://stackoverflow.com/a/3451640/1541165) and in Java (https://stackoverflow.com/a/8858601/1541165), but I don't know either of those languages.

Could someone help translate this to PHP perhaps? Or give guidance on how to solve this problem in a PHP environment?

Thanks.

Community
  • 1
  • 1
gtilflm
  • 1,389
  • 1
  • 21
  • 51

1 Answers1

1

Port to PHP from https://stackoverflow.com/a/8858601/1541165

<?php

$array = array(1,2,3,4,4,5,5,6,7,8,10);

$modes = array();

$maxCount = 0;
for($i = 0; $i < count($array); $i++){
        $count = 0;
        for($j = 0; $j < count($array); $j++){
                if ($array[$j] == $array[$i]) $count++;
        }
        if($count > $maxCount){
                $maxCount = $count;
                $modes = array();
                $modes[] = $array[$i];
        } else if ( $count == $maxCount ){
                $modes[] = $array[$i];
        }
}
$modes = array_unique($modes);

print_r($modes);


?>
Community
  • 1
  • 1
logain
  • 1,475
  • 1
  • 12
  • 18