In PHP, what considerations should be made to ensure unique items are added to a shopping cart efficiently?

When adding items to a shopping cart in PHP, it is important to ensure that duplicate items are not added, as this can lead to inaccuracies in the cart total. One way to efficiently handle this is by checking if the item already exists in the cart before adding it. This can be done by comparing the item's unique identifier, such as a product ID, with the existing items in the cart.

// Check if the item already exists in the cart
function addItemToCart($productId, $quantity) {
    if(isset($_SESSION['cart'][$productId])) {
        // Item already exists, update quantity
        $_SESSION['cart'][$productId] += $quantity;
    } else {
        // Item does not exist, add it to the cart
        $_SESSION['cart'][$productId] = $quantity;
    }
}