What is the purpose of initializing an array in a session variable in PHP?

Initializing an array in a session variable in PHP allows you to store and manipulate data across multiple pages during a user's session. This is useful for maintaining stateful information such as shopping cart items, user preferences, or form data. By initializing an array in a session variable, you can easily add, remove, or update elements within the array as the user interacts with your website.

// Initialize an empty array in a session variable
session_start();

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

// Adding an item to the cart
$product_id = 123;
$quantity = 1;

$_SESSION['cart'][$product_id] = $quantity;

// Removing an item from the cart
unset($_SESSION['cart'][$product_id]);

// Updating the quantity of an item in the cart
$_SESSION['cart'][$product_id] = 2;