Adding the values within an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Dave_Richards
Forum Newbie
Posts: 2
Joined: Wed Nov 08, 2006 2:02 pm

Adding the values within an array

Post by Dave_Richards »

Hey all!

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

Function within a class file:

Code: Select all

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:

Code: Select all

$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
brendandonhue
Forum Commoner
Posts: 71
Joined: Mon Sep 25, 2006 3:21 pm

Post by brendandonhue »

I'm not sure if I understand what you're trying to do, but if you want to add the values of an array, you can use array_sum()
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

You are going to have to figure something out in the calling class, or separate the result array and use array functions to do it.
Dave_Richards
Forum Newbie
Posts: 2
Joined: Wed Nov 08, 2006 2:02 pm

Post by Dave_Richards »

thanks for your help guys :) much appreciated.

Will give the code a go tomorrow.

Thanks again
Post Reply