skip to Main Content

I want to calculate the average from a key contained in the array.

Array
(
    [123456] => Array
        (
            [Log] => 2793
            [Approve] => 1724
            [Accept] => 13863
        )

    [123457] => Array
        (
            [Log] => 2606
            [Classify] => 730
            [FirstLineSupport] => 83339
            [Escalate] => 14689501
            [Fulfill] => 14772840
        )

    [123458] => Array
        (
            [Log] => 2700
            [Approve] => 16152972
            [Fulfill] => 73006092
            [Accept] => 729914
            [Review] => 27033
        )
)

In this case I need to calculate the average of key "Fulfill".
So I need to calculate:

(14772840 + 73006092) / 2 = 43889466

I know I can sum the values using:

$sum = array_sum(array_column($arr, 'Fulfill'));

But how can I divide by the number of occurrences of the key?

PHP online: https://onlinephp.io/c/35153

2

Answers


  1. Put the result of array_column() in a variable. Then you can get the length of that array.

    $fulfills = array_column($arr, 'Fulfill');
    $avg = array_sum($fulfills) / count($fulfills);
    
    Login or Signup to reply.
  2. Just one line more:

    $args = array_column($arr, 'Fulfill');
    $sum = array_sum($args)/count($args);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search