How to find average from array in php?
first you need to remove empty values, otherwise average will be not accurate.
so
$a = array_filter($a);
$average = array_sum($a)/count($a);
echo $average;
DEMO
More concise and recommended way
$a = array_filter($a);
if(count($a)) {
echo $average = array_sum($a)/count($a);
}
See here
The accepted answer works for the example values, but in general simply using array_filter($a)
is probably not a good idea, because it will filter out any actual zero values as well as zero length strings.
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);