Reputation: 297
I have a form with two input fields:
Parts Price and Parts Quantity
And user can click a button to add as many as they want.
I need to calculate the parts * the quantity to get a sum. For example, if the user has Part one which is 10 dollars and has a quantity of 2. The second part is 20 dollars with the quantity of 2, the sum should be 60 dollars.
Part 1 * Quantity = sum of part 1
Part 2 * Quantity = sum of part 2
Sum of part 1 + Sum of part 2
This is a simple math equation but i get confused when it comes to arrays.
I tried the following but it only works right if the quantity is 1:
$sumofparts = array_sum($_POST['partsprice']) * array_sum($_POST['partsquantity']);
When i try the code with a part with the price of 10 dollars and a quantity of 2 and another part is 10 dollars with the quantity of 2 the sum should be 40; however I'm getting a sum of 80
Upvotes: 0
Views: 184
Reputation: 54831
Your math is wrong. What you need is to sum results of multiplying
and not multiply sums
. In a simple way it can be done like:
$sum = 0;
foreach ($_POST['partsprice'] as $k => $v) {
$sum += $v * $_POST['partsquantity'][$k];
}
echo $sum;
Upvotes: 1