CodeBlanks Logo Icon CodeBlanks

Adding products to the cart

PHP course · Beginner · Lesson 49/116

Create a products array and add new products to the cart.

Adding products to the cart

In the first lesson you added one product to the cart. Now you'll see how to add multiple products in one go.

PHP has two common ways to append elements: the $cart[] = ... pattern adds a single element; the array_push function can add several elements in one call. When the cart has many products, array_push is handier.

The array_push function

The array_push function appends one or more elements to the end of an array. The first argument is the array variable; the following arguments are the values to add.

For example, array_push($cart, "Notebook", "Eraser") appends "Notebook" and "Eraser" to $cart. You can also append associative arrays: array_push($cart, ["name" => "Notebook", "price" => 40]). The function returns the new length of the array.

Exercise Add two more products to the cart

Now add two more products to the cart. Use array_push($cart, ...) to add ["name" => "Notebook", "price" => 40, "quantity" => 1] and ["name" => "Eraser", "price" => 10, "quantity" => 3]. Place the call before the echo line, so count($cart) returns 3 and the output reads Cart count: 3.

Show example solution
array_push takes $cart first, then two associative arrays. Place the call before the echo line.
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";

Test yourself

  1. What does the $cart[] = ... pattern do?

    • Appends a new element to the array
    • Removes the first element of the array
    • Prints all elements of the array
    • Empties the array
    Show answer

    Appends a new element to the array — Correct. The $cart[] = ... pattern appends a new element to the array.

  2. Complete the array_push call

    $cart = [];
    ____
    
    Show answer
    $cart = [];
    array_push($cart, "Pen");
    
  3. Match each method to its role

    array_push
    appends elements
    $cart[] = ...
    appends one element
    count($cart)
    returns element count
    $cart = []
    creates empty array

All lessons in Beginner