I made an order form using PHP that makes subtotals for each item ordered. How can I make a function/code to display the total for the order in the bottom of the page. I tried to read on PHP.net but couldn't figure it out.
Here is a sample of my code:
$bread = $_POST["bread"];
$cheese = $_POST["cheese"];
$eggs = $_POST["eggs"];
$priceBread = 5;
$priceCheese = 5;
$priceEggs = 3.6;
function subtotal($incomingQuantity, $incomingPrice){
return $incomingQuantity * $incomingPrice;
}
<div id="breadSubtotal">$<?php echo subtotal($bread, $priceBread); ?>
<div id="cheeseSubtotal">$<?php echo subtotal($cheese, $priceCheese); ?></div>
<div id="eggsSubtotal">$<?php echo subtotal($eggs, $priceEggs); ?></div>
I want the total from the subtotals of all the items
</div>
something like this?
$total = 0;
function subtotal($incomingQuantity, $incomingPrice){
global $total;
$sub = $incomingQuantity * $incomingPrice;
$total += $sub;
return $sub;
}
then in the HTML
<div id="total">$<?php echo $total; ?></div>
also, dont forget to make safe your incoming $_POST vars with something like
$bread = htmlspecialchars($_POST["bread"]);
I want the total from the subtotals of all the items
Its really simple to calculate. Try like this
$bread = 2;
$cheese = 3;
$eggs = 4;
$priceBread = 5;
$priceCheese = 5;
$priceEggs = 3.6;
$total = 0;
function subtotal($incomingQuantity, $incomingPrice){
return $incomingQuantity * $incomingPrice;
}
$total += subtotal($bread, $priceBread) ;
$total += subtotal($bread, $priceBread);
$total += subtotal($cheese, $priceCheese);
echo "order total : " + $total;
If am not wrong, you want to calculate the number of each item with the price of the items. So based on that this is how I would do it.
public function getTotal()
{
$total = 0;
$subTotal = func_get_args();
for($a = 0; $a < sizeof($subTotal); $a++)
{
$total += $subTotal[$a];
}
return $total;
}
Test the function
getTotal(subtotal($bread, $priceBread), subtotal($cheese, $priceCheese), subtotal($eggs, $priceEggs));
That's how I would do it, gives you more flexibility
<?php
$bread = $_POST["bread"];
$cheese = $_POST["cheese"];
$eggs = $_POST["eggs"];
//prices
$prices = array('bread'=>5,'cheese'=>5,'eggs'=>3.6);
function calculateOrderTotals($items, $prices){
//result
$result = array('total'=>0, 'subTotal'=>array());
//total
$total = 0;
//calculate subtotal and total
foreach ($items as $item => $nPurchased){
$subTotal = $nPurchased* $prices[$item];
$result['subTotal'][$item] = $subTotal;
$total += $subTotal;
}
//set total
$result['total'] = $total;
//return
return $result;
}
//call function to calculate
$totals = calculateOrderTotals(array('bread'=>$bread,'cheese'=>$cheese,'eggs'=>$eggs), $prices);
?>
<div id="breadSubtotal"><?php echo $totals['subTotal']['bread'];?>
<div id="cheeseSubtotal"><?php echo $totals['subTotal']['cheese']; ?></div>
<div id="eggsSubtotal"><?php echo $totals['subTotal']['eggs']; ?></div>
<div id="total"><?php echo $totals['total']; ?></div>