find the sum of all keys in a map in php

To find the sum of all keys in a map (or associative array) in PHP, you can use a loop to iterate over the keys and add them up. Here's an example code snippet:

main.php
$myMap = array(
    "a" => 1,
    "b" => 2,
    "c" => 3
);

$sum = 0;
foreach ($myMap as $key => $value) {
    $sum += $key;
}

echo $sum; // Output: 6 (1 + 2 + 3)
165 chars
13 lines

In this code, we define a map $myMap with some key-value pairs. Then, we initialize $sum to zero and use a foreach loop to iterate over each key-value pair in the map. We use the $key variable to access the key and add it to the $sum variable. Finally, we output the sum of all keys using echo.

related categories

gistlibby LogSnag