Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: How to take the average of several sets of numbers (assigning variable names?)

  1. #1
    Join Date
    Apr 2013

    How to take the average of several sets of numbers (assigning variable names?)

    I'm still fairly new at PHP, and am trying to put together a program for use by myself and a small number of other people. A very simple program already exists and works. I'd like to add some ways that people can retrieve their own data so that they can analyze it and learn from it.

    People basically just enter a numerical rating at different times of the day. It could be, for example, the outdoor temperature at any given hours. (It isn't, but that is probably the best example.)

    I'd like for people to be able to ascertain their average temperature rating for, say, mornings during the first two weeks of April, 2013. I pretty much understand how to restrict the query to (a) hours between, say, 6 a.m. and noon; and (b) days between April 1 and April 14, 2013.

    A twist arises because some days will have more than one morning rating, e.g., temp is 50 at 6:00 a.m.; 60 at 10:00 a.m.; and 65 at 11:45 a.m. So I need to average those temps and then have just one figure for that date.

    Bear in mind, please, that I'm still very much a beginner and therefore tend to think in quite simplistic ways! This is basically only my second project and I'm content to proceed in very elementary ways, even if they are not the most efficient. (for now, anyway)

    So - I'm imagining a conditional that will say something like: if there is more than one entry for these hours on any given day, then add those entries and average them, and assign the result to variable $morning_temp; else (if there is only one entry for these hours), then assign that entry to variable $morning_temp. Then I would want to add them and take their average.

    I've boxed myself in, however -- I'm assigning all the temps to the same variable name!

    Can anyone tell me please how to get myself out of this corner?

    For the moment, at least, I'd like to stay fairly close to this paradigm, as it's one that I understand and could, with some effort, probably implement. There are probably ways that would be much spiffier and more elegant, but there is a significant risk that I would not, at present, understand them.

    I'm hoping that someone can nudge me in the right direction.

    Thank you!

  2. #2
    Join Date
    Apr 2013
    Should I be creating an array? is that the step that I'm missing?

    (I'm just working at the concept level for the moment - not asking anyone to write code for me.)

    Thank you for any help.

  3. #3
    Join Date
    Apr 2013
    Two additional small points / questions:

    1: Continuing to think about this, I see that my proposed averaging method for a given morning is rather crude. That is, because the temps are not equi-distant in time, their 'average' will be somewhat inaccurate. That is okay for the present. Further refinements can be looked at in due course.

    2: If I'm assigning values to an array, is there any way that I can keep them in chronological order? That is, if I'm taking the average of three values for April 1; then have just a single value for April 2; but again want to take the average of several values for April 5 -- right now, I'm envisioning an if/else set-up that would deal with April 1 and April 5 first, and only then take up April 2 in the else clause. Is there some way that I can have the results show up in chrono order (April 1, April 2, April 5)?

    Thank you for your patience thus far!

  4. #4
    Join Date
    Apr 2013
    Query: would I construct a more complex if/else statement, in order to keep things chronological?


  5. #5
    Join Date
    Mar 2011
    It sounds to me like you need to create a database that would hold this information, which could then be used to analyze it as you like. PHP makes working with databases pretty easy, and hosting services always provide tools for creating them, so you can start off simply enough.

    But the coding questions will boil down to defining your needs more clearly. It's easy enough to suggest methods that would be appropriate to average temperatures for a given time of day across a specified time period, but that might not work for your particular situation. Could you be more specific about what you're trying to do?
    Rick Trethewey
    Rainbo Design

  6. #6
    Join Date
    Apr 2013

    Actually, I already have a database and a small program that works. That is, users can enter data and also retrieve their own data. I'd like to make it more useful to them by enabling them to retrieve just chunks of it. I really did my best in explaining what would help me go to the next step. For example, am I correct in thinking that I need to use an array?

    I really can't think how I could make my question clearer. I'm pretty sure I described the problem accurately.

  7. #7
    Join Date
    Apr 2013
    Again, I'm not asking anyone to write the code. I have some idea of what to write. I'm asking for some informed guidance on the direction I should be looking in. If someone can confirm that basic direction, then I'll have more confidence that I'm not wasting my time heading in the wrong direction.

  8. #8
    Join Date
    Mar 2011
    Well then, I'd repeat my suggestion about working with a database and then proceed with the methods you describe. Good luck!
    Rick Trethewey
    Rainbo Design

  9. #9
    Join Date
    Apr 2013
    I'm hoping that someone will be willing to take my questions seriously and give me an idea of whether I am headed in the right direction. My questions are sincere and I have done my best to pose them articulately and intelligently.

    Thank you to anyone who may be inclined to help!

  10. #10
    Join Date
    Apr 2013
    For example - getting back to the idea of an array. Is that the direction I need to go in?

    Is my idea of averaging by using an if/else conditional a reasonable one?

    Is there some way that I can keep the values for the various dates in chronological order -- even though they will be processed in two different 'batches' (so to speak) using the if/else format?

  11. #11
    Join Date
    Aug 2004
    If, in fact, this is coming from a DB query, then I would agree with the other response that you make the averaging part of the query. Since I don't know how the data is stored in the DB, I can't be sure of the exact approach, but if we assume the observation_timestamp is one column and temperature another, it might be something like....
       DATE(observation_timestamp) AS obs_date,
       AVG(temperature) AS avg_temp             -- this is where the magic happens :)
    FROM your_table_name
       observation_timestamp BETWEEN '2013-03-30 00:00:00' AND '2013-04-05 00:00:00'
       -- the 2 date strings above would actually be variables from your PHP script
       TIME(observation_timestamp) BETWEEN '06:00:00' and '12:00:00'
       -- above time strings might also be variables?
    GROUP BY obs_date          -- where the rest of the magic happens
    ORDER BY obs_date ASC
    Databases are designed from the ground up to be optimized for handling and processing data, so it's good to leverage that efficiency when you can.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  12. #12
    Join Date
    Apr 2013
    NogDog, I really appreciate it that you have replied. Unfortunately I don't understand your reply because it is couched in terms that are different from my question. Are you saying that I don't need to use arrays? Your reply uses code that I am not familiar with, and I cannot tell if it takes into consideration my concerns about averaging the data for a single day and then using that result to calculate an average for the entire period.

  13. #13
    Join Date
    Apr 2013
    If someone would address my actual questions, I would probably understand the answers.

  14. #14
    Join Date
    Aug 2004
    I'm saying that doing the averaging in your PHP application code is not the place where I would do it: I would do it in the DBMS. It's both more efficient (faster) and simpler to do (though "simpler" is in the mind of the beholder, obviously).

    If for some (stubborn ) reason I just didn't want to do it in the database layer, I would probably build a results array in at least 3 dimensions, then loop through it or, in this example, leverage the array_walk() function to do the looping.
    PHP Code:

    = array(
    '2013-04-01' => array(
    'readings' => array(
    '06:04:31' => '52',
    '11:15:42' => '59'
    '2013-04-02' => array(
    'readings' => array(
    '09:55:31' => '58'
    '2013-04-03' => array(
    'readings' => array(
    '07:24:33' => '53',
    '11:15:42' => '59',
    '11:59:59' => '61'

    '&$val, $key',
    'if(count($val["readings"])) {
                $val["avg"] = array_sum($val["readings"]) / count($val["readings"]);
            } else {
                $val["avg"] = "NO DATA";

    // show the results:
    echo "<ul>\n";
    $results as $date => $data) {
    "<li>$date: ".round($data['avg'],1)."</li>\n";
    * 2013-04-01: 55.5
    * 2013-04-02: 58
    * 2013-04-03: 57.7
    Last edited by NogDog; 04-25-2013 at 10:35 PM.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  15. #15
    Join Date
    Apr 2013
    What is the DBMS?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.11471 seconds
  • Memory Usage 3,021KB
  • Queries Executed 13 (?)
More Information
Template Usage (37):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (2)bbcode_code
  • (1)bbcode_php
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (15)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (1)pagenav
  • (1)pagenav_curpage
  • (1)pagenav_pagelink
  • (15)postbit
  • (15)postbit_onlinestatus
  • (15)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (72):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • pagenav_page
  • pagenav_complete
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates