Created
June 22, 2019 02:54
-
-
Save webinista/ec35592460763e52616b1da74fd94306 to your computer and use it in GitHub Desktop.
find the mode of an array using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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