Code Logo

Array Average

Published at24 Jul 2026
PHP Data Structures Easy 0 views
Like0

Write a PHP function that calculates the average (mean) of an array of numbers. Return the average as a float. If the array is empty, return 0.0.

Sum all elements using array_sum() and divide by the count using count(). Cast the result to float to ensure decimal precision. For empty arrays, return 0.0 to avoid division by zero.

Edge cases include empty arrays (return 0.0), single-element arrays (return that element as float), arrays with negative numbers, and arrays with decimal values.

Calculating the average of array elements combines summation and division. The array_sum() function computes the total, and count() returns the number of elements. Casting to float ensures decimal precision in the result.

PHP's array_sum() works with both integer and float arrays. The count() function returns the number of elements. When dividing, PHP performs float division automatically if the result is not an integer. The explicit cast to float ensures consistent return type.

Edge cases include empty arrays (return 0.0 to avoid division by zero), single-element arrays (return that element as float), and arrays with negative values which average correctly.

The function handles both integers and floats in the input array, making it suitable for general-purpose averaging.

Example Input & Output

Example 1
Input
[1,2,3,4,5]
Output
3.0
Example 2
Input
[-5,5]
Output
0.0
Example 3
Input
[10,20,30]
Output
20.0
Example 4
Input
[]
Output
0.0
Example 5
Input
[5]
Output
5.0

Algorithm Flow

Recommendation Algorithm Flow for Array Average
Recommendation Algorithm Flow for Array Average

Solution Approach

Use array_sum($nums) to get the total sum and count($nums) to get the number of elements. If count is 0, return 0.0. Otherwise, divide sum by count and cast to float with (float).

For a manual implementation: initialize $sum = 0, loop with foreach, add each element to $sum, then divide by count($nums) after the loop.

Edge cases: empty array (return 0.0), single element (return that element as float).

Time O(n), Space O(1).

The array_sum() and count() approach is the most concise. For a manual implementation, a foreach loop accumulating values divided by count achieves the same result without built-in functions.

Best Answers

php - Approach 1
<?php
function average($nums) {
    $n = count($nums);
    if ($n === 0) return 0.0;
    return (float)(array_sum($nums) / $n);
}