How to find average from array in php?

Dinesh G picture Dinesh G · Nov 1, 2015 · Viewed 67.6k times · Source

Example:

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

Actually how to find average value from this array excluding empty. please help to resolve this problem.

Answer

Mubin picture Mubin · Nov 1, 2015

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