How to find average from array in php?

a 夏天 提交于 2019-11-26 16:48:43

问题


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.


回答1:


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




回答2:


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);



回答3:


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


来源:https://stackoverflow.com/questions/33461430/how-to-find-average-from-array-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!