How can you prevent the issue of the first item being overwritten when adding a new item to the shopping cart array in PHP?

When adding a new item to the shopping cart array in PHP, the issue of the first item being overwritten can be prevented by using a unique identifier for each item in the cart. This identifier can be the product ID or any other unique value associated with the item. By checking if the item already exists in the cart based on this identifier, we can update the quantity instead of adding a new entry.

// Example code snippet to prevent overwriting the first item in the shopping cart array

// Product details
$product_id = 123;
$product_name = 'Example Product';
$product_price = 10.99;

// Check if the product already exists in the cart
if(isset($_SESSION['cart'][$product_id])) {
    // Update the quantity of the existing item
    $_SESSION['cart'][$product_id]['quantity'] += 1;
} else {
    // Add a new item to the cart
    $_SESSION['cart'][$product_id] = array(
        'name' => $product_name,
        'price' => $product_price,
        'quantity' => 1
    );
}