Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math average with php

Tags:

php

math

average

Time to test your math skills...

I'm using php to find the average of $num1, $num2, $num3 and so on; upto an unset amount of numbers. It then saves that average to a database.

Next time the php script is called a new number is added to the mix.

Is there a math (most likely algebra) equation that I can use to find the average of the original numbers with the new number included. Or do I need to save the original numbers in the database so I can query them and re-calculate the entire bunch of numbers together?

like image 896
Marcus Avatar asked Jan 10 '10 02:01

Marcus


People also ask

How do I average in PHP?

Here, we will discuss the approach to implement to find the average of the column in the SQL database using PHP in Xampp server as follows. Create a table in a database. Insert the records into the table using PHP. PHP's code to find an average of a particular column.

How do I find the average of 3 numbers in PHP?

// The Average of Numbers $number1 = ['number3']; $number2 = ['number3']; $number3 = ['number3']; // How Many Numbers are in Our Set $numbersInSet = 3; // Get the Sum of the Numbers $average = $sum / $numbersInSet; echo "The average of the three numbers you entered is<b> $average<p>"; php.

How do you find the average of an array in PHP?

You can either do $count = count($a); or just do if($a) . Both are good enough solutions. I would use if($a) which saves on calling count() on empty arrays, but is harder to understand for those starting to learn the language.

Can you do calculations in PHP?

PHP has a set of math functions that allows you to perform mathematical tasks on numbers.


2 Answers

array_sum($values) / count($values)
like image 196
Isra Avatar answered Sep 19 '22 07:09

Isra


If what you mean by average is the 'mean' and you don't want to store all numbers then store their count:

$last_average = 100;
$total_numbers = 10;
$new_number = 54;

$new_average = (($last_average * $total_numbers) + $new_number) / ($total_numbers + 1);
like image 29
slebetman Avatar answered Sep 22 '22 07:09

slebetman