如何在php中找到数组的平均值?

时间:2022-03-02 21:44:28

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.

实际上如何从这个数组中找出不包括空的平均值。请帮忙解决这个问题。

3 个解决方案

#1


28  

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

DEMO

More concise and recommended way

更简洁和推荐的方式

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

See here

看这里

#2


7  

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

#3


0  

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

#1


28  

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

DEMO

More concise and recommended way

更简洁和推荐的方式

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

See here

看这里

#2


7  

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

#3


0  

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