Page 2 of 2

Re: Merge two variables

Posted: Sun Jan 04, 2009 10:07 pm
by sk8bft
For each "food" i have also added a "price". I was able to multiply the 'price' with the 'amount' for each item. But I can't find a way to sum this so I'll get the total price as well. Here's the code. While $value is working fine, the $total allways gives me zero.

Code: Select all

 
$total = $_POST['food']['price'] * $_POST['food']['amount'];
 
$msg = "";
foreach ($_POST["food"] as $food) {
if ($food["check"] && $food["amount"]) { // checked and at least one
$msg .= $food["amount"] . " "; // number
$msg .= $food["check"]; // name
$value = $food['price'] * $food['amount'];
$msg .= $value; // price 
 
if ($food["extra"]) $msg .= " with " . $food["extra"]; // extra
$msg .= "\n";
}
}
 
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message\n $msg $total";
 
Any ideas?

Re: Merge two variables

Posted: Sun Jan 04, 2009 10:47 pm
by requinix
The food data is in the form $_POST["food"][item number][data type] so $_POST['food']['price'] doesn't make sense. Keep that in mind.

To get a grand total you need to get the totals for each food item. You don't need the total until after that one loop you have so there's not much code to add.

Code: Select all

$msg = ""; $total = 0;
foreach ($_POST["food"] as $food) {
if ($food["check"] && $food["amount"]) { // checked and at least one
$msg .= $food["amount"] . " "; // number
$msg .= $food["check"]; // name
$value = $food['price'] * $food['amount']; $total += $value;
$msg .= $value; // price
 
if ($food["extra"]) $msg .= " with " . $food["extra"]; // extra
$msg .= "\n";
}
}
 
// you can use sprintf to format a number to #0.00 format
// the dollar sign makes it look like a normal price, the %..f is a special syntax
$total_asprice = sprintf('$%0.2f', $total);
 
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message\n $msg $total_asprice";

Re: Merge two variables

Posted: Sun Jan 04, 2009 11:10 pm
by sk8bft

Code: Select all

$total += $value;
I think I got this. It basically means that total = total + value, so for every new value, it will be added to the total, right?

Your suggestion works perfect. Again, thank you so much for your help.