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

Q: Gold Miner - PHP Associative Arrays Task

+2 votes

You are given a sequence of strings, each on a new line. Every odd line on the console is representing the type of the gold (e.g. Yellow, Rose, White, and so on), and its karats. Your task is to collect the resources while you receive "stop" and print each on a new line.

Print the resources and their quantities in format:

"{type} –> {karats}K"

The karats inputs will be in the range [1 … 24 000]

Examples:

gold miner php associative arrays task

asked in PHP category by user ak47seo

1 Answer

+1 vote

Here is my solution:

<?php

$input = readline();
$goldArr = [];

while ($input !== "stop") {

    $type = $input;
    $carats = intval(readline());

    if (!key_exists($type, $goldArr)) {
        $goldArr[$type] = $carats;
    } else {
        $goldArr[$type] += $carats;
    }

    $input = readline();

}

foreach ($goldArr as $type => $carats) {
    echo "$type -> $carats" . "K" . PHP_EOL;
}
answered by user andrew
...