How can you prevent overwriting data in a session when adding multiple items to a shopping cart in PHP?

When adding multiple items to a shopping cart in PHP, you can prevent overwriting data in a session by storing the cart items as an array within the session. This way, each item can be added to the array without overwriting the existing data.

// Start or resume the session
session_start();

// Check if the cart array exists in the session, if not, create it
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

// Add item to the cart array
$item = array(
    'id' => 123,
    'name' => 'Product Name',
    'price' => 19.99
);

$_SESSION['cart'][] = $item;