Skip to content

Instantly share code, notes, and snippets.

@webinista
Created June 22, 2019 02:54
Show Gist options
  • Save webinista/ec35592460763e52616b1da74fd94306 to your computer and use it in GitHub Desktop.
Save webinista/ec35592460763e52616b1da74fd94306 to your computer and use it in GitHub Desktop.
find the mode of an array using PHP
function array_mode($$arr) {
/*
Count the frequency of occurrence of values in the array.
This will make each duration value into a key, with its frequency as the
value
*/
$counts = array_count_values($$arr);
/*
Get all of the count values and find the unique values, then sort them,
highest to lowest. This gives us the highest count value.
*/
$freq = array_unique($counts);
arsort($freq);
// Grab the maximum frequency value, which will be the first one.
$max = array_shift($freq);
// Returns items in $counts that match this max value.
$max_match = array_filter($counts, function($dur) use ($max) {
return $dur === $max;
});
// Remember durations are the keys!
$mode = array_keys($max_match);
// If the array is multimodal, return the whole thing. Otherwise, return first one.
return (count($mode) > 1) ? $mode : $mode[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment