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.
// 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;
Related questions
-
eval PHP string-based
-
string Boolean expression transformation
-
PHP date calculation numerical value