0, "green" => 0, "blue" => 0, ); foreach ($hand as $h) { $colors = array(); preg_match_all("/(\d+) (red|green|blue)/", $h, $colors); foreach (array_combine($colors[2], $colors[1]) as $key => $value) { $bag[$key] = max($bag[$key], $value); } } print_r($bag); $sum += $bag['red'] * $bag['green'] * $bag['blue']; } fclose($fd); echo $sum;