Jump to content

adding (math) array values


XJTRy

Recommended Posts

I have populated and array with values from a table column. There are only three values returned 25, 35, and 50. How can I echo the sum of the numbers?

 

$query = "SELECT worth FROM onlinegm"; 
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
echo $row['worth'];
echo "<br />";
}

Link to comment
https://forums.phpfreaks.com/topic/148640-adding-math-array-values/
Share on other sites

  Quote

 

Thanks, I've been trying without success.

 

$query = "SELECT worth FROM onlinegm"; 
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
echo $row['worth'];
echo "<br />";
}

echo "Sum of values = ".array_sum($row['worth'])."<br>"; 

$query = "SELECT worth FROM onlinegm";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
   echo $row['worth'];
   $values[] = $row['worth'];
   echo "<br />";
}

echo "Sum of values = ".array_sum($values)."<br>"; 

 

or.. if you don't actually need to store those values in array

 

$query = "SELECT worth FROM onlinegm";
$result = mysql_query($query) or die(mysql_error());
$sum = 0;
while($row = mysql_fetch_array($result)){
   echo $row['worth'];
   $sum += $row['worth'];
   echo "<br />";
}

echo "Sum of values = $sum<br>"; 

 

Thanks again.

 

I prefer the first method of pushing data into array as it's consistent with data use in actionscript. I made the mistake of assuming the returned data was already in an array and available for purge. I did this with some concepts last night as well.

 

Your help is appreciated!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.