Home >Backend Development >PHP Problem >What is the function to find the average of an array in php?
There is no function to directly calculate the average of an array in php, but you can use the array_sum(), count() functions and the "/" operator to calculate the average of the array. Implementation steps: 1. Use the "array_sum($arr)" statement to calculate the sum of array elements; 2. Use the "count($arr)" statement to calculate the array length; 3. Use the "array element sum/array length" statement to calculate Just average.
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php does not provide direct array average The function. If you want to find the average value of a php array, you can use the array_sum(), count() functions and the "/" operator.
Implementation steps:
Step 1: Use array_sum() to calculate the sum of array elements;
array_sum () function can return the sum of all values in the array
array_sum($array)
Step 2: Use count() to calculate the length of the array;
count() function returns the elements in the array The number of , that is, the length of the array.
count($array,$mode);
Parameters | Description |
---|---|
array | Required . Specifies the array to count. |
mode | Optional. Specifies the mode of the function. Possible values:
|
If you are looking for the length of a one-dimensional array, the second parameter $mode
can be omitted. If it is a multi-dimensional array, Then the $mode
parameter needs to be set to 1.
Step 3: Use the "/" operator to find the average
数组元素和/数组长度
Implementation example:
<?php header("content-type:text/html;charset=utf-8"); $arr = array(1,2,3,4,5,6,7,8,9,10); var_dump($arr); $sum=array_sum($arr); echo "数组的和为:".$sum."<br>"; $len=count($arr); echo "数组长度:".$len."<br>"; $average=$sum/$len; echo "数组平均值:".$average."<br>"; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What is the function to find the average of an array in php?. For more information, please follow other related articles on the PHP Chinese website!