- Sum
15- Count
5- Mean
15 / 5 = 3
Find Average of N Numbers in PHP
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 > 0checks 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,
forloops, 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.
10, 15, 20, 25, 30 gives sum 100, count 5, mean 20.
Intuition and examples
- Sum
100- Count
5- Mean
20
Live preview
Enter comma-separated numbers and click Run.
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
function averageOfN(n):
if n <= 0: return error
sum <- 0
repeat n times:
read x
sum <- sum + x
return sum / nAverage of N numbers from stdin
Reads values from CLI input and prints average as float.
<?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";
?>Average from a fixed array
Useful when data is already in memory.
<?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
🔄 Input / output examples
| Input values | Average |
|---|---|
1, 2, 3, 4, 5 | 3.000000 |
10, 15, 20, 25, 30 | 20.000000 |
Edge cases and pitfalls
N == 0
Never divide by zero.
Bad tokens
Validate user input before casting.
Floating point
Float math can have tiny rounding differences.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Running sum | O(N) | O(1) |
| Store full list | O(N) | O(N) |
Summary
- Mean: sum divided by count.
- Code: one loop for sum, one division at end.
- Watch-outs:
N = 0and input validation.
The arithmetic mean is the common school-level average: add all values and divide by how many values you have.
9 people found this page helpful
