Skip to content
Advertisement

How to find average 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 average value from this array excluding empty. please help to resolve this problem.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement