codegurukool.com · Free coding tutorials & online compiler

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

Steps

  1. Read the $cart array.
  2. line_total multiplies price by quantity.
  3. Press Run to see the bill.
  4. 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

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;
?>

Run this code in the online editor

← PHP MySQL prepared statements