Php sum variable in while loop

I need to โ€œsumโ€ the values โ€‹โ€‹of the variables, while, here is my example:

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

The above code throws if I put echo $price;, for example:

19 15 20 13 10

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

How can I do this with php?

thank

+3
source share
2 answers

Just initialize the variable outside of your loop, for example:

$total_price = 0;

and increase this number inside the loop:

$total_price += $row['price'] * $row['order_q'];
+12
source

eg.

$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 this inside the sql query.

SELECT Sum(price*order_q) as total FROM ...
+11
source