SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Zealot
    Join Date
    Sep 2008
    Location
    Bristol ,England
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Counting the values of an array

    Hi does any body know what the best way to loop through an array and add int values ? Basicly I am gathering info from a database, I am then using a foreach loop to loop through the array and then trying to find a way to add all the int values of the returned data together like 1+4+6 etc.
    Any help would be grateful

  2. #2
    SitePoint Zealot zalucius's Avatar
    Join Date
    Jul 2007
    Location
    Denmark
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm assuming you're using a MySQL database.
    You can add up the values directly in the SQL query:
    Code SQL:
    SELECT SUM(the_field) AS summed_value FROM TABLE_NAME

    This will give you one value in the result: "summed_value" which is all the "the_field" added together.

    A quick PHP example:
    Code PHP:
    $result= mysql_query('SELECT SUM(the_field) AS summed_value FROM table_name');
    $data = mysql_fetch_assoc($result);
    echo  $data['summed_value'];
    zalucius

  3. #3
    SitePoint Zealot
    Join Date
    Sep 2008
    Location
    Bristol ,England
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect, might have learn more mysql!! Thanks

  4. #4
    SitePoint Zealot
    Join Date
    Sep 2008
    Location
    Bristol ,England
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry one more thing, basicly I am building a rating system and thats why I needed to add up the values but I now need to find an average amount, is the a way I can do this in mysql?

  5. #5
    SitePoint Zealot zalucius's Avatar
    Join Date
    Jul 2007
    Location
    Denmark
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    SQL also have an AVG() function, which gets the avarage of a collection of values.
    Just replace the SUM() with AVG() and see what happens
    zalucius

  6. #6
    SitePoint Zealot
    Join Date
    Sep 2008
    Location
    Bristol ,England
    Posts
    177
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect, again thank you

  7. #7
    SitePoint Addict
    Join Date
    May 2006
    Location
    Amsterdam
    Posts
    206
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if the values didn't already exist in a db or you don't want to add the slight overhead of an additional query ... try php

    Google search term "php sum array values"


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •