Array Average
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
Algorithm Flow

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
function average($nums) {
$n = count($nums);
if ($n === 0) return 0.0;
return (float)(array_sum($nums) / $n);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
