find the variance of all keys in a map in php

To find the variance of all keys in a map in PHP, you can use the following code:

main.php
function map_variance(array $map): float {
    $key_sum = 0;
    $key_count = count($map);
    foreach ($map as $key => $value) {
        if (!is_numeric($key)) {
            throw new InvalidArgumentException('All keys must be numeric');
        }
        $key_sum += $key;
    }
    $key_mean = $key_sum / $key_count;
    $variance = 0;
    foreach ($map as $key => $value) {
        $variance += pow($key - $key_mean, 2);
    }
    $variance /= $key_count;
    return $variance;
}
484 chars
18 lines

This function takes an associative array as an argument and returns the variance of all keys in the map. It calculates the sum of all keys, and then the mean key value. It then calculates the variance by taking the sum of the squared differences from the mean and dividing by the number of keys in the map. If any keys in the map are not numeric, an InvalidArgumentException is thrown.

related categories

gistlibby LogSnag