What are the best practices for handling changes in a shopping cart without losing previous data in PHP?
When handling changes in a shopping cart without losing previous data in PHP, it is important to store the cart data in a session variable. This allows the data to persist across different pages and visits to the website. When a change is made to the cart, such as adding or removing items, the session variable should be updated accordingly to reflect the changes.
// Start or resume the session
session_start();
// Initialize the cart data if it doesn't exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Add an item to the cart
function addToCart($item) {
$_SESSION['cart'][] = $item;
}
// Remove an item from the cart
function removeFromCart($index) {
unset($_SESSION['cart'][$index]);
}
// Update the quantity of an item in the cart
function updateCartQuantity($index, $quantity) {
$_SESSION['cart'][$index]['quantity'] = $quantity;
}
// Clear the cart
function clearCart() {
$_SESSION['cart'] = [];
}