Jump to content

PHP Average number


ewok13

Recommended Posts

Hi.

 

Im trying to make a PHP code that will find the average number.

 

What I want is, a lot of input fields where you can write a number in.

 

Then my code should take these numbers and divide them with the amount of input fields that has been written in.

 

So that some fields you don't have to write a number, and the code will still give you a correct average.

 

My code so far:

 

<?php
if (isset($_POST['calc']))
{
$m=$_POST['mat'];
$e=$_POST['da'];
$s=$_POST['eng'];
$f=$_POST['fys'];
$h=$_POST['bio'];
$p=$_POST['geo'];
$ave=($m+$e+$s+$f+$h+$p)/;
}
?>

<a href="" onclick="return hs.htmlExpand(this, { headingText: 'Beregn dit Gennemsnit:' })">
<b>Beregn dit Gennemsnit:   <?php echo $ave;?></b><br></br>
</a>
<div class="highslide-maincontent">
<form id="gennemsnit" name="form1" method="post" action="">
Matematik<input name="math" type="text" id="mat" size="3" maxlength="4" /><br />
Dansk<input name="eng" type="text" id="da" size="3" maxlength="4" /><br />
Engelsk<input name="sci" type="text" id="eng" size="3" maxlength="4" /><br />
Fysik<input name="fil" type="text" id="fys" size="3" maxlength="4" /><br />
Biologi<input name="he" type="text" id="bio" size="3" maxlength="4" /><br />
Geografi<input name="pe" type="text" id="geo" size="3" maxlength="4" /></td><br />
<input name="calc" type="submit" id="calc" value="Beregn"/><br /><br />
</form>

 

What I need is the code of how to divide with the amount of input fields that has been written in.

 

Thx for any help :)

Link to comment
Share on other sites

I think this should work. Top function determines if the value sent is a number. The code is scalable too, just add more fields as required to your html form. Would need reworking however if your form were to include fields not required for the average calculation but required for something else, eg username or something.

 

Let me know if it works. Not tested.

 

 

//could do to change this as not good for internet exploder.
if (isset($_POST['calc']))
{
//this function will return the value of the field if it was a number, else it will return 0 and reduce the master divide fo the average.
function numCheck(&$masterDiv,$a){
if(ctype_digit($a)
{
return $a;
}
else{
--$masterDiv;
return 0;
}


//number to divide with to get the average
$masterDiv = count($_POST) - 1;//minus your input button
//running total of values
$runningTotal = 0;

//get all the keys of the post array
$keys = array_keys($_POST);
//loop through based on the count of the $_POST  
for($i=0 ; $i < count($_POST) ; ++$i)
     {
          //as the $key array is based exactly on the $array array the key is pos $i in the array:
          $theKey =  $keys[$i];
      
          //now we have the associative key we can easily get the value
          $theValue =  $array[$theKey];
         
          //now do what ever you want with the data, provided the current is not the calc button
if($theKey != 'calc')
{
//using the function we built at the top this should add the value sent to the runningTotal if it is a number, else it will return a zero for the runningTotal and reduce by 1 the masterDivide meaning it will not be including when calculating the average
$runningTotal += numCheck($masterDiv,$theValue);
}
      }

//now calculate the average based on the mastser divide and running total.
$ave=$runningTotal / $masterDiv;
}

Link to comment
Share on other sites

Here's a simpler solution

if (isset($_POST['calc']))
{
    $m = trim($_POST['mat']);
    $e = trim($_POST['da']);
    $s = trim($_POST['eng']);
    $f = trim($_POST['fys']);
    $h = trim($_POST['bio']);
    $p = trim($_POST['geo']);

    $count = ($m!=''?1:0) + ($e!=''?1:0) + ($s!=''?1:0) + ($f!=''?1:0) + ($h!=''?1:0) + ($p!=''?1:0);

    $ave = ($m+$e+$s+$f+$h+$p) / $count;
}

 

Although, for the purposes of scalability I would put the POST fields into an array. E.g. $_POST['vars']['mat'], $_POST['vars']['da'], etc. The code then could be simplified even further and would work with any number of fields without any modifications needed.

 

if (isset($_POST['calc']))
{
    $total = 0;
    $count = 0;
    foreach($_POST['vars'] as $value)
    {
        $value = trim($value);
        $total += floatval($value);
        if($value!=0) { $count++; }
    }

    $ave = $total / $count;
}

Link to comment
Share on other sites

A slightly different array method -

 

<?php
function _empty($var){
    return ($var != ''); // filter empty strings
}

if (isset($_POST['calc'])){
$values = array_map('trim',$_POST['vars']); // trim all 
$values = array_filter($values, "_empty"); // remove empty entries
$ave = array_sum($values) / count($values); // calc average
echo $ave;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.