tags:

views:

50

answers:

6

I have this code:

foreach ($cartContents as $item => $itemQty)
    echo "$item <br /> $itemQty   <br />  $price";

It loops through some items and prints the name, quantity and price. I would then like to print a total of all the prices added together. Is there a way to get this figure?

+8  A: 

Assuming $itemQty and $price are both numeric, this should work:

$total = 0;
foreach ($cartContents as $item => $itemQty) {
    echo "$item <br /> $itemQty   <br />  $price";
    $total += $itemQty * $price;
}

echo "Total: $total<br />";
Mike
A: 
$total = 0;
foreach ($cartContents as $item => $itemQty) {
    echo "$item <br /> $itemQty   <br />  $price";
    $total += ($itemQty * $price);
}

echo $total;

This doesn't make too much sense as you have no other mention of $price

This is also assuming that $price is a number rather than a string e.g. £5.00

Lizard
A: 

Where is the $price variable coming from in your example? Assuming it's valid, then you would simply do this:

$totalPrice = 0;
foreach ($cartContents as $item => $itemQty)
{
    echo "$item <br /> $itemQty   <br />  $price";
    $totalPrice += $itemQty * $price;
}

echo $totalPrice ;
DisgruntledGoat
A: 

Set up a variable called $totalprice, and then every loop add the $price to $totalprice. Here's the code, but the synatax is probably wrong, haven't programmed php in a while:

//declare variable $totalprice (I forget how)
foreach ($cartContents as $item => $itemQty)
{
echo "$item <br /> $itemQty   <br />  $price";
$totalprice+=$price*$itemQty;
}

Edit: Ok, that makes me laugh, 3 people with the same answer at the same time.

meman32
Actually, your solution is subtly - but crucially - different than the other two.
CaseySoftware
Oops, forgot item quantity, I'll fix that now.
meman32
A: 

Try:

$total = 0;
foreach ($cartContents as $item => $itemQty) {
    $total += $price;
    echo "$item <br /> $itemQty   <br />  $price";
}
echo "<br/><br/>Total: $total";

I assume that you left out where you're setting the value of $price above. This is very basic code; I recommend that you find a simple PHP tutorial to learn basic syntax. There are a million on Google.

Lucas Oman
+2  A: 
  $sum=0;
  foreach ($cartContents as $item => $itemQty){

    echo "$item <br /> $itemQty   <br />  $price";
    $sum += $price * $itemQty;

  }

  echo $sum;
Prasoon Saurav