如何从php中的数组中找到平均值? [英] How to find average from array in php?

查看:27
本文介绍了如何从php中的数组中找到平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

$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.

推荐答案

首先需要去除空值,否则平均值会不准确.

first you need to remove empty values, otherwise average will be not accurate.

所以

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

演示

更简洁推荐的方式

$a = array_filter($a);
if(count($a)) {
    echo $average = array_sum($a)/count($a);
}

见这里

这篇关于如何从php中的数组中找到平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆