Find Average of N Numbers in PHP

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
Loops & I/O

What you’ll learn

  • The arithmetic mean formula and a running sum loop in PHP.
  • A stdin-style loop program and an array-based program.
  • Why N > 0 checks and float division matter.
  • A live preview for comma-separated values.

Overview

Read N values, add them, and divide by N. This page shows both interactive input and array input paths.

Prerequisites

Comfort with loops, arrays, and basic PHP input is enough.

  • Variables, for loops, and functions.
  • Basic understanding of float vs integer values.

What is the average here?

The arithmetic mean of x1, x2, ..., xN is:

mean = (x1 + x2 + ... + xN) / N, where N > 0.

Formal definition

For values x1..xN, mean = (1/N) * Σ xi, for N >= 1.

Worked example

10, 15, 20, 25, 30 gives sum 100, count 5, mean 20.

Intuition and examples

1..5Mean 3
Sum
15
Count
5
Mean
15 / 5 = 3
10..30Mean 20
Sum
100
Count
5
Mean
20

Live preview

Enter comma-separated numbers and click Run.

Live result
Press "Run" to see count, sum, and mean.

Algorithm

Goal: compute average of N values.

Read N

If N <= 0, stop.

Initialize sum

Set sum = 0.

Loop N times

Read one value, add to sum.

Divide

Compute sum / N.

📜 Pseudocode

Pseudocode
function averageOfN(n):
    if n <= 0: return error
    sum <- 0
    repeat n times:
        read x
        sum <- sum + x
    return sum / n
1

Average of N numbers from stdin

Reads values from CLI input and prints average as float.

php
<?php
function findAverageFromStdin(int $n): float
{
    if ($n <= 0) return 0.0;
    $sum = 0.0;
    for ($i = 0; $i < $n; $i++) {
        $line = trim(fgets(STDIN));
        $sum += (float)$line;
    }
    return $sum / (float)$n;
}

$n = 5;
echo "Enter $n numbers:\n";
$avg = findAverageFromStdin($n);
echo "Average: " . number_format($avg, 6) . "\n";
?>
2

Average from a fixed array

Useful when data is already in memory.

php
<?php
function averageFromArray(array $a): float
{
    $n = count($a);
    if ($n <= 0) return 0.0;
    $sum = 0.0;
    foreach ($a as $x) {
        $sum += (float)$x;
    }
    return $sum / (float)$n;
}

$data = [10, 15, 20, 25, 30];
echo "Average = " . number_format(averageFromArray($data), 6) . "\n";
?>

Optimization

One pass is enough. Keep only running sum and count.

For streaming data, update mean online without storing full history.

Watch precision for very large or very tiny values.

❓ FAQ

Add all N values to get the sum, then divide by N. Formula: mean = (x1 + x2 + ... + xN) / N.
If you want decimal output consistently, cast sum or N to float before division. It avoids accidental integer-style thinking and keeps the result clear.
Division by zero causes an error. Always check N > 0 before dividing.
Single-pass averaging is O(N) time and O(1) extra space when you keep only a running sum.
No. Mean is sum/count. Median is the middle value after sorting.

🔄 Input / output examples

Input valuesAverage
1, 2, 3, 4, 53.000000
10, 15, 20, 25, 3020.000000

Edge cases and pitfalls

Zero

N == 0

Never divide by zero.

Input

Bad tokens

Validate user input before casting.

Precision

Floating point

Float math can have tiny rounding differences.

⏱️ Time and space complexity

ApproachTimeExtra space
Running sumO(N)O(1)
Store full listO(N)O(N)

Summary

  • Mean: sum divided by count.
  • Code: one loop for sum, one division at end.
  • Watch-outs: N = 0 and input validation.
Did you know?

The arithmetic mean is the common school-level average: add all values and divide by how many values you have.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful