Merge two variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

sk8bft
Forum Newbie
Posts: 14
Joined: Sat Jan 03, 2009 5:55 pm

Re: Merge two variables

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Merge two variables

Post 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";
sk8bft
Forum Newbie
Posts: 14
Joined: Sat Jan 03, 2009 5:55 pm

Re: Merge two variables

Post 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.
Post Reply