CodeBlanks Logo Icon CodeBlanks

Displaying the cart

PHP course · Beginner · Lesson 50/116

List and display cart products with foreach.

Displaying the cart

After adding products to the cart, the customer needs to see it. The foreach loop is the easiest way to walk through each element and print it.

When you write foreach ($cart as $product), PHP assigns each element of $cart to $product in turn. Inside the body you reach a product's properties with $product["name"], $product["price"] and $product["quantity"]. To put each product on its own line, use \n.

Accessing associative arrays inside foreach

To reach a property in an associative array, write the key in square brackets: $product["name"]. This works like a plain array index, but the index is a key, not a number.

To combine several properties in one echo, use the dot (.) operator. For example, echo $product["name"] . " - " . $product["price"] . " USD"; outputs Pen - 25 USD. You can also do arithmetic: $product["price"] * $product["quantity"].

Exercise List the cart line by line

Iterate over each product in the cart with foreach and print it on its own line with echo. Each line follows <name> - <price> USD x<quantity> (e.g. Pen - 25 USD x2). End each line with \n. Keep the existing echo line.

Show example solution
Write foreach ($cart as $product); in the body, echo $product["name"], $product["price"] and $product["quantity"] joined by dots.
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";
}

Test yourself

  1. What does foreach ($cart as $product) do?

    • It sorts the $cart array
    • It empties the $cart array
    • It assigns each element of $cart to $product in turn
    • It returns the length of $cart
    Show answer

    It assigns each element of $cart to $product in turn — Correct. foreach assigns each element of the array to $product in turn and runs the body for each one.

  2. Complete the foreach body

    foreach ($cart as $product) {
        echo ____;
    }
    Show answer
    foreach ($cart as $product) {
        echo $product["name"];
    }
  3. Match the foreach parts

    foreach
    iterates each element
    as $product
    names each element
    $product["name"]
    accesses the name
    $product["price"]
    accesses the price

All lessons in Beginner