PHP Average of N Numbers Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Is the Average of N Numbers?

The average (arithmetic mean) of N numbers is their sum divided by the count.

Remember
average = (a₁ + a₂ + … + aₙ) / N

Example: 1, 2, 3, 4, 5
  sum = 15, N = 5
  average = 15 / 5 = 3
ValuesSumNAverage
1, 2, 3, 4, 51553
10, 15, 20, 25, 30100520
2, 4623
1, 2321.5

How to Find the Average of N Numbers in PHP

Sum every value once, then divide by the count — guard empty input first.

  1. Reject N <= 0 or an empty array (no division by zero).
  2. Iterate the N values (loop or array_sum).
  3. Accumulate a running sum.
  4. Return sum / N as a float.
MethodIdeaTimeBest for
Running sum + NLoop N times with a fixed listO(N)Interviews, demos
Array helperSum with foreach, divide by countO(N)Reusable default
array_sum / countBuilt-in sum and lengthO(N)Concise application code

Pseudocode

Pseudocode
function Average(values):
    n = length of values
    if n == 0:
        return error   // or a documented sentinel

    sum = 0
    for each value in values:
        sum = sum + value

    return sum / n

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Formulaaverage = sum / N
GuardNever divide when N <= 0
PHP float15 / 5 is 3; 3 / 2 is 1.5
Shortcutarray_sum($a) / count($a)
Not medianMedian needs sorting; average does not
1..5sum 15 → average 3

Live Preview

Enter comma-separated numbers to see the sum, count, and average.

Comma-separated numbers. Tap a chip or type your own list.

Result
values = [1, 2, 3, 4, 5]
sum = 15, N = 5
average = 3

Worked Walkthrough — 1, 2, 3, 4, 5

Add every value, then divide by the count.

Calculation
values: 1, 2, 3, 4, 5
N = 5

sum = 0
  + 1 → 1
  + 2 → 3
  + 3 → 6
  + 4 → 10
  + 5 → 15

average = 15 / 5 = 3

PHP Programs

Start with a running-sum helper and fixed N. Then average any array with foreach, and finish with array_sum / count.

Example 1 — Running Sum with Fixed N

Validate N, loop N times over a values list, keep a running total, then divide.

php
<?php
function averageOfNNumbers(int $n, array $values): float
{
    if ($n <= 0) {
        return 0.0;
    }

    $total = 0.0;
    for ($i = 0; $i < $n; $i++) {
        $total += $values[$i];
    }
    return $total / $n;
}

$n = 5;
$values = [1, 2, 3, 4, 5];
$result = averageOfNNumbers($n, $values);
echo "The average of the entered numbers is: $result\n";

How It Works

  1. Return 0.0 if $n <= 0 (documented sentinel).
  2. Add $values[0] through $values[$n - 1] into $total.
  3. Divide once after the loop: $total / $n.
  4. PHP keeps decimals for float division, so 1 / 2 is 0.5.
  5. Sample 1…5 prints 3.

Example 2 — Average from an Array

Reusable helper: sum every element with foreach, then divide by count.

php
<?php
function averageFromArray(array $values): float
{
    $n = count($values);
    if ($n === 0) {
        return 0.0;
    }

    $total = 0.0;
    foreach ($values as $value) {
        $total += $value;
    }
    return $total / $n;
}

$data = [10, 15, 20, 25, 30];
$avg = averageFromArray($data);
echo "Average = $avg\n";

How It Works

  1. Reject an empty array before dividing.
  2. Sum every element in one foreach pass.
  3. Divide by count($values) for the mean.
  4. 10+15+20+25+30 = 100 → average 20.
  5. Prefer this shape in interviews: one clear helper.

Example 3 — array_sum / count

Same formula with built-ins — still guard empty arrays.

php
<?php
function mean(array $values): float
{
    $n = count($values);
    if ($n === 0) {
        return 0.0;
    }
    return array_sum($values) / $n;
}

$data = [1, 2, 3, 4, 5];
echo mean($data) . "\n";

How It Works

  1. Return early when count($values) is 0.
  2. array_sum adds every element in one call.
  3. Divide the sum by the count once.
  4. Same math as the foreach loop — just more compact.
  5. Sample 1…5 prints 3.

Edge Cases & Pitfalls

Check these before calling the solution done.

Empty

Never divide by N = 0

Empty lists are undefined. Return an error or a documented sentinel.

N = 1

Average = itself

A single value’s average is that value.

Negatives

Allowed

The formula works with negative numbers too.

Median

Different from median

Average is sum/count. Median needs a sorted middle value.

Time and Space Complexity

ProgramTimeExtra space
Running sum / foreach / array_sumO(N)O(1) beyond the input
Storing all inputs firstO(N)O(N)

One pass is enough. You do not need to sort for an arithmetic mean.

Key Takeaways

  • Formula: average = sum / N.
  • Guard: never divide when N is zero.
  • Shortcut: array_sum($a) / count($a) for non-empty arrays.
  • Test: 1…5 → 3; 10…30 step 5 → 20; 1,2 → 1.5.

One line: add every value, divide by the count — that is the average.

Frequently Asked Questions

Add all N numbers, then divide by N. Formula: average = sum / N. Use floating-point division so decimals are kept.
Division by zero is undefined. If the count is 0 (empty list), do not compute an average.
No. Average is sum divided by count. Median is the middle value after sorting.
Yes. For a non-empty array: array_sum($a) / count($a). Always guard empty arrays before dividing.
O(N) — each value is visited once. A running sum uses O(1) extra space.

Next: Biggest of Three Numbers

Find the largest among three values with simple comparisons.

Biggest of three tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

16 people found this page helpful