php 如何从php中的数组中找到平均值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33461430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find average from array in php?
提问by Dinesh G
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.
实际上如何从这个数组中找到不包括空的平均值。请帮助解决这个问题。
回答by Mubin
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;
More concise and recommended way
更简洁推荐的方式
$a = array_filter($a);
if(count($a)) {
echo $average = array_sum($a)/count($a);
}
回答by Don't Panic
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.
接受的答案适用于示例值,但一般来说,简单地使用array_filter($a)
可能不是一个好主意,因为它会过滤掉任何实际的零值以及零长度的字符串。
Even '0'
evaluates to false, so you should use a filter that explicitly excludes zero length strings.
即使'0'
评估为 false,因此您应该使用明确排除零长度字符串的过滤器。
$a = array_filter($a, function($x) { return $x !== ''; });
$average = array_sum($a) / count($a);
回答by Martyn Shutt
echo array_sum($a) / count(array_filter($a));