Home › PHP Tutorial › Live project: Shopping cart bill
Live project: Shopping cart bill
Total a shopping cart with tax.
Use arrays, functions and loops to print a bill.
What you will build
- A cart stored as an array of items
- A function that totals one line
- Subtotal, 18% tax and grand total
Steps
- Read the
$cartarray. line_totalmultiplies price by quantity.- Press Run to see the bill.
- Change the prices and quantities.
Run it
Press Run to see the project work. Then change the data in the editor and run it again.
Challenge
- Add a discount for totals above 500.
- Print the bill as an HTML table.
Example code
<?php
$cart = [
["name" => "Pen", "price" => 10, "qty" => 3],
["name" => "Notebook", "price" => 45, "qty" => 2],
["name" => "Bag", "price" => 500, "qty" => 1],
];
function line_total($item) {
return $item["price"] * $item["qty"];
}
$total = 0;
foreach ($cart as $item) {
$t = line_total($item);
$total += $t;
echo $item["name"] . " x" . $item["qty"] . " = " . $t . PHP_EOL;
}
$tax = round($total * 0.18);
echo "Subtotal: " . $total . PHP_EOL;
echo "GST 18%: " . $tax . PHP_EOL;
echo "Total: " . ($total + $tax) . PHP_EOL;
?>