Skip to content
PHP Logo

How can PHP variables be properly utilized to handle multiple prices for products in a shopping cart?

To handle multiple prices for products in a shopping cart, you can use an associative array where the keys are the product IDs and the values are the prices. This way, you can easily retrieve the price of a product by referencing its ID in the array.

php
// Define an associative array to store product prices
$product_prices = [
    'product1' => 10.99,
    'product2' => 24.99,
    'product3' => 14.99
];

// Retrieve the price of a product by referencing its ID
$product_id = 'product2';
$product_price = $product_prices[$product_id];
echo "The price of product2 is: $" . $product_price;