Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding values within an array

Status
Not open for further replies.

DaveyRichards

Programmer
Nov 8, 2006
14
GB
Hey all!

was wondering if you could help me with my problem. I have the following code:

Function within a class file:

public static function getSomething($database){
$query = "SELECT important FROM tblPurchases WHERE purchase = 3 AND buyer = 5";

$result = $database->Select($query);
return $result;
}

PHP Web Page:

$function= pFunction::getSomething($_DATABASE);

foreach($function as $result) {
$important = $result;

$count++;
}

This code counts the amount of records that match the SQL criteria and places the important variable into an array. However I would like to extract all values of "important" (which is an integer value) and add them together to produce a sum of all of the "important" values. Could somebody please advice me as to what I need to add to my code to acheive this.

Thanks
 
Modify your code in your foreach statement to do the math while it's collecting the data:

Code:
foreach($function as $result) {
$important = $result;
$sumImportant .= $important;
$count++;
}

print "Total = $sumImportant";

This should give you the sum of all the important entries.



"If the only prayer you said in
your whole life was, 'thank you,'
that would suffice."
-- Meister Eckhart
 
Actually, this:
Code:
$sumImportant .= $important;
will just concatenate the numbers, and you'll end up with somethig like 2234647663534747637390927837 intead of the sum of the values.

try

$sumimportant=$sumimportant+$important;

don't forget to initialize your variable $sumimportant to 0 before the for each loop.

$sumimportant=0;

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
thanks for your help guys :) much appreciated.

Will give the code a go tomorrow.

Thanks again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top