Computing the total
Multiply each product's price and quantity and compute the cart total.
Computing the total
To compute the total of the cart you use a technique called a running total (accumulator). You first initialize a $total variable to 0; then, with foreach, you add each product's amount to it.
Each product's amount is price × quantity. So you write $total += $product["price"] * $product["quantity"] to grow the running total at each step. When the loop ends, $total holds the cart's grand total.
Multiplication and addition inside foreach
Writing $total += expression is the same as $total = $total + expression; it is a compound assignment operator. It is shorter and clearer.
In the cart calculation, the expression is $product["price"] * $product["quantity"]. Multiplication happens before addition, so no parentheses are needed. For three products (25×2, 40×1, 10×3) the running totals are 50, 90 and 120; the final total is 120.
Exercise Compute and print the cart total
Now compute the cart's total. Initialize $total to 0. With a second foreach, add each product's price × quantity to $total. After the loop, print Total: <total> USD (e.g. Total: 120 USD); end the line with \n.
Show example solution
" . $total . " USD\n".
Example solution:
<?php
// Initialize the cart array and add the first product
$cart = [];
$cart[] = ["name" => "Pen", "price" => 25, "quantity" => 2];
// Add two more products with array_push
array_push($cart, ["name" => "Notebook", "price" => 40, "quantity" => 1], ["name" => "Eraser", "price" => 10, "quantity" => 3]);
echo "Cart count: " . count($cart) . "\n";
// List the cart with foreach
foreach ($cart as $product) {
echo $product["name"] . " - " . $product["price"] . " USD x" . $product["quantity"] . "\n";
}
// Compute the total
$total = 0;
foreach ($cart as $product) {
$total += $product["price"] * $product["quantity"];
}
echo "Total: " . $total . " USD\n";
Test yourself
-
How is the accumulator initialized?
- $total = "";
- $total = [];
- $total = -1;
- $total = 0;
Show answer
$total = 0; — Correct. The accumulator starts at zero; each product's amount grows it.
-
Add the product amount to $total
$total += $product["price"] ____Show answer
$total += $product["price"] * $product["quantity"]; -
Match the calculation concepts
- $total = 0
- initializes the accumulator
- $total +=
- adds to the running total
- price * quantity
- line total for a product
- $total
- stores the grand total