What are best practices for structuring PHP code to handle scenarios where a shopping cart may be empty or contain items?
When dealing with scenarios where a shopping cart may be empty or contain items, it is important to check the cart's contents before performing any operations on it to avoid errors. One common approach is to use conditional statements to handle both cases separately, ensuring that the code behaves correctly regardless of the cart's state.
// Check if the shopping cart is empty
if(empty($_SESSION['cart'])) {
echo "Your shopping cart is empty.";
} else {
// Loop through the cart items and display them
foreach($_SESSION['cart'] as $item) {
echo "Item: " . $item['name'] . ", Price: $" . $item['price'] . "<br>";
}
}