What are the best practices for storing and retrieving shopping cart data using sessions in PHP?

When storing and retrieving shopping cart data using sessions in PHP, it is important to serialize the data before storing it in the session and unserialize it when retrieving it. This ensures that complex data structures, such as arrays or objects, can be properly stored and retrieved from the session. Additionally, always check if the session data exists before attempting to retrieve it to avoid errors.

// Storing shopping cart data in session
$cart = ['item1', 'item2', 'item3'];
$_SESSION['cart'] = serialize($cart);

// Retrieving shopping cart data from session
if(isset($_SESSION['cart'])) {
    $cart = unserialize($_SESSION['cart']);
    // Use $cart array for further processing
}