How can you ensure that the product ID is saved along with the quantity in a PHP session when adding items to a shopping cart?

To ensure that the product ID is saved along with the quantity in a PHP session when adding items to a shopping cart, you can create an associative array where the key is the product ID and the value is the quantity. This way, you can easily update the quantity for a specific product ID when adding more items to the cart.

// Start the session
session_start();

// Check if the product ID and quantity are provided
if(isset($_POST['product_id']) && isset($_POST['quantity'])) {
    $product_id = $_POST['product_id'];
    $quantity = $_POST['quantity'];

    // Initialize the cart if it doesn't exist
    if(!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
    }

    // Update the quantity for the product ID in the cart
    if(array_key_exists($product_id, $_SESSION['cart'])) {
        $_SESSION['cart'][$product_id] += $quantity;
    } else {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}