find the average of all keys in a map in php

To find the average of all keys in a map (or associative array) in PHP, you can use the array_keys() and array_sum() functions. Here's an example:

main.php
<?php
$map = array(
    'key1' => 2,
    'key2' => 4,
    'key3' => 6,
    'key4' => 8,
);

$keys = array_keys($map);
$sum = array_sum($keys);
$count = count($keys);
$average = $sum / $count;

echo "Average of all keys is: " . $average;
?>
240 chars
16 lines

This code creates a map with four keys and values, then uses array_keys() to extract an array of just the keys. It then uses array_sum() to find the sum of all the keys, and divides that by the count of the keys to get the average. Finally, it prints out the average of all the keys in the map.

related categories

gistlibby LogSnag