Home  »  ArticlesGuidesHow ToProgrammingTechnology   »   How to Calculate the Rolling Average of Numbers in PHP

How to Calculate the Rolling Average of Numbers in PHP

Before we get to show you how to calculate the rolling average of an array or series of numbers it is important to understand what it is.

What is a Rolling Average?

A rolling average, also known as a moving average, is a statistical calculation used to analyze data over a specific time period. It smooths out short-term fluctuations and highlights longer-term trends or patterns in the data.

To calculate a rolling average, you select a window or interval of time (e.g., days, weeks, months) and compute the average value of the data points within that window. As you move forward in time, the window “rolls” or shifts, including new data points and excluding older ones. This process continues until you have computed the rolling average for all the available data points.

The rolling average is often used to analyze time series data, such as stock prices, sales figures, or temperature readings. It helps to eliminate noise or volatility in the data, making it easier to identify underlying trends or patterns. By using a rolling average, you can obtain a smoother representation of the data, which can aid in making predictions or detecting long-term changes.

Different types of rolling averages exist, including the simple moving average (SMA), exponential moving average (EMA), and weighted moving average (WMA). Each type has its own calculation method and is suited for different applications.

Calculate the Rolling Average in PHP

Here we will use PHP as an example to calculate a rolling average of an array of numbers you can use a loop to iterate through the array of values and calculate the average for each window of elements. Here’s an example code snippet that demonstrates the process:

function calculateRollingAverage($numbers, $windowSize) {
    $rollingAverage = [];
    $sum = 0;

    for ($i = 0; $i < count($numbers); $i++) {
        $sum += $numbers[$i];

        if ($i >= $windowSize) {
            $sum -= $numbers[$i - $windowSize];
            $rollingAverage[] = $sum / $windowSize;
        } elseif ($i + 1 >= $windowSize) {
            $rollingAverage[] = $sum / ($i + 1);

    return $rollingAverage;

// Example usage
$numbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
$windowSize = 3;

$rollingAvg = calculateRollingAverage($numbers, $windowSize);

In this example, the calculateRollingAverage function takes two parameters: $numbers (the array of numbers) and $windowSize (the size of the rolling window). It initializes an empty array $rollingAverage to store the calculated rolling averages.

The function then iterates through the $numbers array using a for loop. It keeps track of the sum of the current window of elements using the variable $sum. At each iteration, it adds the current element to $sum and checks if the window size has been reached.

If the window size has been reached or exceeded, it subtracts the first element of the previous window from $sum and calculates the average by dividing $sum by the window size. The calculated average is then added to the $rollingAverage array.

Finally, the function returns the $rollingAverage array containing the calculated rolling averages.

In the example usage section, an array [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] is provided, and a window size of 3 is specified. The calculateRollingAverage function is called with these parameters, and the resulting rolling averages are printed using print_r.

The output of the example would be:

    [0] => 4
    [1] => 6
    [2] => 8
    [3] => 10
    [4] => 12
    [5] => 14
    [6] => 16
    [7] => 18

These values represent the rolling averages for each window of size 3 in the original array. The above formula can be applied to any other programming language.

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.