Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have to "sum" variable's values in while, here us my example :

while($row = mysql_fetch_array($result)){
  $price= $row['price'] * $row['order_q'];
}

The code above will output if I put echo $price; for example:

19 15 20 13 10

I want something like : sum($price) or array_sum($price) to count all the results of while loop. So, that i want to count: 19+15+20+13+10 = 77

How can I do it with php?

Thanks

share|improve this question
    
why you do not use array_sum() ? –  Chandresh Apr 26 '12 at 8:22

2 Answers 2

up vote 3 down vote accepted

Simply initialize a variable outside your loop for example:

$total_price = 0;

and increment this number inside your loop:

$total_price += $row['price'] * $row['order_q'];
share|improve this answer
    
Thank you very much, that is what i want to do ^^ –  user1358069 Apr 26 '12 at 8:27

e.g.

$total = 0;
while($row = mysql_fetch_array($result)){
  $price= $row['price'] * $row['order_q'];
  $total += $price;
}
echo 'total: ', $total;

Or - if all you want from the query is the total - you can do it "within" the sql query.

SELECT Sum(price*order_q) as total FROM ...
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.