user3933456
user3933456

Reputation: 21

PHP: how to make a sum inside a "for each" cycle?

I've made a foreach loop that print some variables found in an xml file:

foreach ($xml->result->rowset->row as $row)
{
    echo $row["price"] . " " . $row["product"] . "</br>";
}

I would like to get the sum of all the "prices" shown. How can i do?

Upvotes: 0

Views: 406

Answers (5)

PHP Learner
PHP Learner

Reputation: 111

$sum=0;
foreach ($xml->result->rowset->row as $row)
    {
        echo $row["price"] . " " . $row["product"] . "</br>";
        $sum +=$row["price"];
    }
echo $sum;

just try this code!!

Upvotes: 0

Dhiraj Wakchaure
Dhiraj Wakchaure

Reputation: 2706

$sum = 0; 
foreach ($xml->result->rowset->row as $row)
{
    echo $row["price"] . " " . $row["product"] . "</br>";
    $sum += $row["price"] ;
}

echo $sum ; 

isnt that simple ?

Upvotes: 1

Tibor B.
Tibor B.

Reputation: 1690

Simply add it to a new variable:

$sum = 0;
foreach ($xml->result->rowset->row as $row) {
  echo $row["price"] . " " . $row["product"] . "<br />";
  $sum += $row["price"];
}

echo $sum . "<br />";

Upvotes: 1

Ende Neu
Ende Neu

Reputation: 15783

Store the count in a variable:

$total = 0;
foreach ($xml->result->rowset->row as $row) {
  echo $row["price"] . " " . $row["product"] . "</br>";
  $total += $row['price']; // assumed row_price is some integer
}
echo $total;

Upvotes: 1

John Conde
John Conde

Reputation: 219824

Just have a variable add up those values as you iterate:

$total = 0; // start with zero
foreach ($xml->result->rowset->row as $row)
{
    $total += $row["price"]; // add price to total
    echo $row["price"] . " " . $row["product"] . "</br>";
}
echo $total; // echo out total amount

Upvotes: 3

Related Questions