Project: Shopping cart
Overview of the 5-lesson shopping cart project: store products in an array and compute totals.
Project: Shopping cart
In this 5-lesson project you'll build a shopping cart. Each lesson adds one piece, and by the final lesson you'll have a complete working app.
You'll use what you learned before:
- output with
echo - variable assignment
- looping with
foreach - arithmetic operators
You'll also learn to store multiple products in a single variable using an array. Ready? Let's start.
Arrays and associative arrays
An array is a way to hold many values in a single variable. An empty array is created with $cart = []; a new element is appended with $cart[] = ....
When a product has several properties (name, price, quantity) you use an associative array. Keys and values are paired with =>: ["name" => "Pen", "price" => 25, "quantity" => 2]. You reach a property with $product["name"].
Exercise Add the first product to the cart
In this lesson you'll write the first piece of the cart. Create an empty array called $cart. Add the first product as an associative array with $cart[] using ["name" => "Pen", "price" => 25, "quantity" => 2]. Then print Cart count: 1 with echo, using count($cart) and a \n at the end of the line.
Show example solution
An empty array is created with []; a product is appended as an associative array via $cart[]. count($cart) returns the number of elements.
Example solution:
<?php
// Initialize the cart array and add the first product
$cart = [];
$cart[] = ["name" => "Pen", "price" => 25, "quantity" => 2];
echo "Cart count: " . count($cart) . "\n";
Test yourself
-
Why does a cart use an array?
- Because an array stores a single value
- Because it holds many products in one variable
- Because an array stores only numbers
- Because an array replaces a database
Show answer
Because it holds many products in one variable — Correct. An array holds many values in a single variable, which suits a cart.
-
Define an empty array
$cart ____;Show answer
$cart = []; -
Match the array concepts
- Empty array
- $cart = []
- Append element
- $cart[] = ...
- Associative array
- name => value
- Array length
- count($cart)