Home >Backend Development >PHP Problem >What is the function of summing and averaging of php arrays?
There is an array summation function "array_sum()" in PHP, which can calculate the sum of all elements in a one-dimensional array; but there is no function that directly calculates the average of an array. If you want to find the average value of a PHP array, you can use the array_sum(), count() functions and the "/" operator. Methods: 1. Use the "array_sum($arr)" statement to calculate the sum of the array elements; 2. Use "count( $arr)" statement to calculate the array length; 3. Use the "array elements and/array length" statement to find the average.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
Array summation is provided in php Function "array_sum()", but does not provide a function to directly find the average of an array.
array_sum($arr)You can calculate the sum of all elements in a one-dimensional array
<?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; ?>
So what do you do if you want to ask for the average value of a PHP array?
In PHP, it can be implemented using array_sum(), count() functions and the "/" operator.<?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 of summing and averaging of php arrays?. For more information, please follow other related articles on the PHP Chinese website!