settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Sum by Town - PHP Associative Arrays Task

+3 votes

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

 

 

asked in PHP category by user john7

1 Answer

+2 votes
 
Best answer

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;
}
answered by user andrew
selected by user golearnweb
...