Are there alternative methods to improve the efficiency of the shopping cart function in PHP?

The efficiency of the shopping cart function in PHP can be improved by implementing session variables to store cart data instead of using cookies. This reduces the amount of data being transferred between the client and server, leading to faster load times and better performance.

// Start or resume the session
session_start();

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

// Add item to cart
function addToCart($item_id, $quantity) {
    $_SESSION['cart'][$item_id] += $quantity;
}

// Remove item from cart
function removeFromCart($item_id) {
    unset($_SESSION['cart'][$item_id]);
}

// Get total items in cart
function getTotalItemsInCart() {
    return array_sum($_SESSION['cart']);
}