开发者

PHP Calculate Total of Looped Items

开发者 https://www.devze.com 2023-01-06 00:14 出处:网络
I have this co开发者_StackOverflow中文版de: foreach ($cartContents as $item => $itemQty) echo \"$item <br /> $itemQty<br />$price\";

I have this co开发者_StackOverflow中文版de:

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?


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 />";


$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


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 ;


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.


  $sum=0;
  foreach ($cartContents as $item => $itemQty){

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

  }

  echo $sum;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消