Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find average from array in php?

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.

like image 632
Dinesh G Avatar asked Nov 01 '15 10:11

Dinesh G


People also ask

How do you find the average of an array?

Simple approach to finding the average of an array We would first count the total number of elements in an array followed by calculating the sum of these elements and then dividing the obtained sum by the total number of values to get the Average / Arithmetic mean.

How do I calculate average in PHP?

$avg = $total/$rows; echo $avg; As you are using string variables in numeric calculations, PHP is converting it wrongly. The 1,806 is taken as 1.

How can I calculate average?

Average This is the arithmetic mean, and is calculated by adding a group of numbers and then dividing by the count of those numbers. For example, the average of 2, 3, 3, 5, 7, and 10 is 30 divided by 6, which is 5.


1 Answers

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

like image 153
Mubin Avatar answered Sep 18 '22 13:09

Mubin