How to find average from array in php?

前端 未结 4 2088
盖世英雄少女心
盖世英雄少女心 2020-12-03 06:47

Example:

$a[] = \'56\';
$a[] = \'66\';
$a[] = \'\';
$a[] = \'58\';
$a[] = \'85\';
$a[] = \'\';
$a[] = \'\';
$a[] = \'76\';
$a[] = \'\';
$a[] = \'57\';


        
相关标签:
4条回答
  • 2020-12-03 07:02

    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

    0 讨论(0)
  • 2020-12-03 07:03

    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);
    
    0 讨论(0)
  • 2020-12-03 07:04
    echo array_sum($a) / count(array_filter($a));
    
    0 讨论(0)
  • 2020-12-03 07:18

    As a late look, item controls should be done with numeric check. Otherwise something like this $array = [1.2, 0.33, [123]] will corrupt the calculation:

    // Get numerics only.
    $array = array_filter($array, fn($v) => is_numeric($v));
    
    // Get numerics only where value > 0.
    $array = array_filter($array, fn($v) => is_numeric($v) && ($v > 0));
    

    Finally:

    public static function average(array $array, bool $includeEmpties = true): float
    {
        $array = array_filter($array, fn($v) => (
            $includeEmpties ? is_numeric($v) : is_numeric($v) && ($v > 0)
        ));
    
        return array_sum($array) / count($array);
    }
    

    Credits: froq.util.Arrays

    0 讨论(0)
提交回复
热议问题