How to find average from array in php?

How to find average from array in php?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Calculating Averages from Arrays with Null Values in PHP

Calculating an average from a dataset seems trivial at first glance, but it quickly becomes problematic when your data contains null values or empty strings. In many real-world scenarios—like processing CSV imports, API responses, or user-generated content—arrays frequently contain gaps that need to be ignored during aggregation. Consider this specific dataset where you have numeric values mixed with empty entries:

$a[] = '56';
$a[] = '66';
$a[] = '';
$a[] = '58';
$a[] = '85';
$a[] = '';
$a[] = '';
$a[] = '76';
$a[] = '';
$a[] = '57';

If you simply iterate through this array and sum the values without filtering, PHP will treat empty strings as 0 when cast to integers. This would skew your average significantly. The core challenge is distinguishing between a missing value (which should be excluded from both the sum and the count) and an actual numeric value.

To solve this, you must first normalize the data before performing mathematical operations. The most robust approach involves filtering out empty strings or null values while ensuring that the remaining elements are valid integers or floats.

Here is a straightforward implementation using a standard PHP loop:

$sum = 0;
$count = 0;

foreach ($a as $value) {
    // Remove whitespace and check if the string is not empty
    $trimmedValue = trim($value);
    
    if (empty($trimmedValue)) {
        continue; // Skip empty strings
    }

    // Ensure we are dealing with a number before adding
    if (is_numeric($trimmedValue)) {
        $sum += (float)$trimmedValue;
        $count++;
    }
}

$average = count > 0 ? $sum / $count : 0;
echo $average; 

This method is explicit and easy to debug. You manually control the logic, ensuring that empty() checks handle both empty strings and nulls. The is_numeric() check adds a safety layer against non-numeric strings like "abc", preventing warnings or type coercion errors.

However, as your codebase grows, writing manual loops for common operations can become repetitive. This is where modern PHP frameworks shine. If you are working within the Laravel ecosystem, the framework provides powerful collection methods that handle exactly this kind of data sanitization.

You can leverage collect() to create a collection from your array, then chain methods like filter() and map to clean the data. Alternatively, Laravel's Avg helper isn't built-in by default in older versions, but you can replicate the functionality elegantly using the collection API:

$average = collect($a)
    ->filter(fn($value) => !empty(trim($value))) // Exclude empty strings/nulls
    ->map(fn($value) => (float)$value)           // Cast to float for precision
    ->avg();                                      // Calculate average

This functional approach is often more readable and less prone to "off-by-one" errors or logic bugs in manual loops. It clearly expresses the intent: filter bad data, cast good data, then aggregate.

One common pitfall developers encounter is forgetting that empty() returns true for strings containing only whitespace. If your input comes from a form or an external API, it might look like " " rather than "". The trim() function inside the conditional ensures these are caught and excluded. Another consideration is division by zero; if all values in the array are empty, the calculation must default to 0 rather than triggering a warning.

While standard PHP arrays work well for simple scripts, if you are building larger applications where data integrity is critical, integrating tools from LaravelCompany can provide additional utilities for data validation and sanitization that go beyond basic array manipulation. These resources often include community-tested packages that streamline complex data processing tasks.

Ultimately, the choice between a manual loop and a collection method depends on your project's needs. For quick scripts, the explicit foreach loop offers maximum control. For maintainable applications, especially within Laravel, chaining collection methods provides a cleaner, more expressive solution.

Our network