How to find average value from array in php?

Example:

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

Actually, how to find the average value from this array, excluding empty ones. help solve this problem.

+32
source share
3 answers

you must first remove the empty values, otherwise the average will not be accurate.

So

 $a = array_filter($a); $average = array_sum($a)/count($a); echo $average; 

Demo

A shorter and recommended way

 $a = array_filter($a); if(count($a)) { echo $average = array_sum($a)/count($a); } 

look here

+65
source

The accepted answer works for example values, but generally just using array_filter($a) is probably not a good idea, because it will filter out any actual null values ​​as well as strings with zero length.

Even '0' evaluates to false, so you should use a filter that explicitly excludes zero-length strings.

 $a = array_filter($a, function($x) { return $x !== ''; }); $average = array_sum($a) / count($a); 
+15
source
 echo array_sum($a) / count(array_filter($a)); 
+2
source

All Articles