// simulation code: return array(680 => array('name' => 'Test1', 'amount' => 1), 517 => array('name' => 'Test2', 'amount' => 99), 1 => array('name' => 'Test3', 'amount' => 12345)); } function extract_ids($arr) { return array_keys($arr); } function get_prices($ids) { // real code: $sql = 'SELECT id,pris FROM tabel WHERE `id` IN (' . implode(',', $ids) . ')'; // execute $sql // $res = array(); // while(something) { // $res[$row['id']] = $row['pris']; // } // return $res; // simulation code: return array(680 => 123, 517 => 456, 1 => 789); } function calc_total($arr, $prices) { $sum = 0; foreach($arr as $id => $value) { $sum += ($value['amount'] * $prices[$id]); } return $sum; } $arr = get_base_data(); $ids = extract_ids($arr); $prices = get_prices($ids); $total = calc_total($arr, $prices); echo $total; ?>