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

#### Hybrid View

1. Registered User
Join Date
Apr 2013
Posts
16

## 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. Registered User
Join Date
Apr 2013
Posts
16
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. Registered User
Join Date
Apr 2013
Posts
16
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. Registered User
Join Date
Apr 2013
Posts
16
Query: would I construct a more complex if/else statement, in order to keep things chronological?

.

5. Registered User
Join Date
Mar 2011
Posts
1,252
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?

6. Registered User
Join Date
Apr 2013
Posts
16
rtrethewey,

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. Registered User
Join Date
Apr 2013
Posts
16
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. Registered User
Join Date
Mar 2011
Posts
1,252
Well then, I'd repeat my suggestion about working with a database and then proceed with the methods you describe. Good luck!

9. Registered User
Join Date
Apr 2013
Posts
16
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?

10. Registered User
Join Date
Apr 2013
Posts
16
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!

11. 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....
Code:
```SELECT
DATE(observation_timestamp) AS obs_date,
AVG(temperature) AS avg_temp             -- this is where the magic happens :)
FROM your_table_name
WHERE
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
AND
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.

12. Registered User
Join Date
Apr 2013
Posts
16
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. Registered User
Join Date
Apr 2013
Posts
16
If someone would address my actual questions, I would probably understand the answers.

14. 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:
``` <?php\$results = 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'        )    ));array_walk(    \$results,    create_function(        '&\$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";foreach(\$results as \$date => \$data) {    echo "<li>\$date: ".round(\$data['avg'],1)."</li>\n";}echo "</ul>\n"; ```
Outputs:
Code:
```* 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.

15. Registered User
Join Date
Apr 2013
Posts
16
Here's the thing about stubbornness . . . I don't really have a choice because there are things I understand and things that I don't understand. So I have to ask questions in language that I understand, and I have to hope that someone will be kind enough to try to understand my questions and also to answer them in terms that I would understand. I don't think that's really stubbornness, although it is certainly a limitation.

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
•

"

"

## X vBulletin 4.2.2 Debug Information

• Page Generation 0.17267 seconds
• Memory Usage 3,432KB
• Queries Executed 13 (?)
Template Usage (34):
• (2)bbcode_code
• (1)bbcode_php
• (1)footer
• (1)forumjump
• (1)forumrules
• (1)gobutton
• (15)memberaction_dropdown
• (1)navbar
• (1)navbar_moderation
• (1)navbar_noticebit
• (1)navbar_tabs
• (2)option
• (1)pagenav
• (1)pagenav_curpage
• (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
Included Files (27):
• ./global.php
• ./includes/class_bootstrap.php
• ./includes/init.php
• ./includes/class_core.php
• ./includes/config.php
• ./includes/functions.php
• ./includes/class_friendly_url.php
• ./includes/class_hook.php
• ./includes/class_bootstrap_framework.php
• ./vb/vb.php
• ./vb/phrase.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 (73):
• 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_foruminfo
• global_state_check
• global_bootstrap_complete
• global_start
• style_fetch
• global_setup_complete
• 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
• notices_check_start
• notices_noticebit
• process_templates_complete
• friendlyurl_redirect_canonical
• pagenav_page
• pagenav_complete
• bbcode_fetch_tags
• bbcode_create
• postbit_factory
• postbit_display_start
• postbit_imicons
• bbcode_parse_start
• bbcode_parse_complete_precache
• bbcode_parse_complete
• postbit_display_complete
• memberaction_dropdown
• tag_fetchbit_complete
• forumrules
• navbits
• navbits_complete