find the mode of all values in a map in php

To find the mode of all values in a map (or hash table) in PHP, you can use a combination of array_count_values() and array_keys() functions.

Here's an example implementation:

main.php
<?php
function mapMode(array $map)
{
    // Count the frequency of each value
    $values = array_count_values($map);
    
    // Find the most frequently occuring value(s)
    $maxFrequencies = array_keys($values, max($values));
    
    // Return the mode(s)
    return $maxFrequencies;
}
291 chars
13 lines

In this implementation, the array_count_values() function takes the input array as an argument and returns an associative array where the keys are the unique values in the array and the values are their respective frequencies.

The array_keys() function is then used to find the keys (i.e., values) that correspond to the maximum frequency in the resulting array. Finally, the function returns an array of the most frequently occuring value(s).

Usage:

main.php
$map = array("dog" => 2, "cat" => 1, "bird" => 1, "fish" => 2);
$mode = mapMode($map);
print_r($mode); // Output: Array ( [0] => dog [1] => fish )
147 chars
4 lines

gistlibby LogSnag