[Solved] Sum by Town - PHP Associative Arrays Task

  

3
Topic starter

Read towns and incomes (on a single line) and print an array holding the total income for each town

Print the towns in their natural order as object properties.

Examples:

sum by town php associative arrays task

1 Answer
2

This is my solution:

<?php
 
$input = explode(', ', readline());
 
$towns = [];
 
for ($i = 0; $i < count($input); $i += 2) {
    if (!isset($towns[$input[$i]])) {
        $towns[$input[$i]] = 0;
    }
    $income = intval($input[$i + 1]);
    $towns[$input[$i]] += $income;
}
foreach ($towns as $key => $value) {
    echo "$key => $value" . PHP_EOL;
}
Share: