Akash Nayee Akash Nayee - 1 year ago 63
PHP Question

Sum of an array in php

I have a while loop below that runs a query and pulls back some values into an associative array, however I can't seem to get the array to sum using array_sum().

if ($availableBooks->num_rows > 0) {
while($row = $availableBooks->fetch_assoc()) {
$allBooks = $row["price"];
$totalCost = array_sum($allBooks);
echo $totalCost;

If I echo $allBooks on it's own, I get "121" which is made up of the three values in my database '1', '2', '1' but as you can see I'm trying to sum them up to get an output of '4'.

Currently I'm not getting any output from the above.

Any help would be appreciated

Answer Source
   if ($availableBooks->num_rows > 0) {
            while($row = $availableBooks->fetch_assoc()) {
               $allBooks[] = $row["price"];      
   $totalCost =  array_sum($allBooks);
   echo $totalCost;}

The array_sum should go outside the while loop.Try the code a bove and let me know.

--------- Edit ----- jszobody solution is way much better then trying to fix the code. That's if you don't need the the prices of the books individually.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download