In what scenarios would it be beneficial to calculate the percentage of a voucher amount on each individual item's price in PHP?
Calculating the percentage of a voucher amount on each individual item's price in PHP can be beneficial when you want to apply a discount proportionally across multiple items in a shopping cart. This ensures that the discount is distributed fairly based on the price of each item. By calculating the percentage of the voucher amount on each item's price, you can maintain accurate pricing and provide customers with a clear understanding of the discount they are receiving.
<?php
// Voucher amount
$voucherAmount = 10;
// Array of item prices
$itemPrices = array(20, 30, 40, 50);
// Calculate total price of items
$totalPrice = array_sum($itemPrices);
// Calculate percentage of voucher amount on each item's price
foreach($itemPrices as $price) {
$discount = ($price / $totalPrice) * $voucherAmount;
$discountedPrice = $price - $discount;
echo "Item price: $price, Discounted price: $discountedPrice\n";
}
?>