Home>Article>Backend Development> How to find the average value of an array avg in php
Implementation steps: 1. Use the array_sum() function to calculate the sum of all elements in the array, the syntax "$sum=array_sum($arr);"; 2. Use the count() function to calculate the length of the array, the syntax "$len=count($arr);"; 3. Use the "/" operator to divide the sum of elements by the array length to obtain the array average avg, the syntax is "$avg=$sum/$len;".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use array_sum() and The count() function is used to find the average avg of an array.
Implementation steps:
Step 1. Use the array_sum() function to calculate the sum of all elements in the array
$sum=array_sum($arr);
Step 2: Use the count() function to calculate the length of the array (the number of elements in the array)
$len=count($arr);
Step 3: Use the "/" operator Divide the sum of elements by the length of the array to get the array average avg
$avg=$sum/$len;
Implementation example:
"; $len=count($arr); echo "数组长度:".$len."
"; $avg=$sum/$len; echo "数组平均值:".$avg."
"; } $arr=array(1,2,3,4,5,6,7,8,9,10); var_dump($arr); f($arr); $arr=array(2,4,6,8,10); var_dump($arr); f($arr); ?>
Function description
1. array_sum() function
array_sum() function can calculate all the values in the array The sum of the elements and returns the sum of the elements.
array_sum($array)
If all elements in$array
are integers, return an integer value; if one or more of the values are floating point numbers, return a float Points.
If there are elements of non-numeric typein
$array, PHP will convert them into a numeric value (PHP is a weak language type and will be based on the value of the variable , automatically convert the variable to the correct data type), if the conversion fails, it will be used as a 0 value to participate in the calculation.
#2. count() function
The method to get the length of an array in PHP is very simple, PHP provides us with two functions to calculate the length of an array, namely the count() and sizeof() functions.
The count() function can count the number of all elements in the array, or the number of attributes in the object. Its syntax format is as follows:
count($array , $mode )
The parameter description is as follows:
Tip: If $array is neither an array nor an object, the count() function will return 1; if $array is equal to NULL, the count() function Return 0.
Example 1: Length of one-dimensional array
Example 2: Length of two-dimensional array
sizeof() function is an alias of count() function, that is, the function and usage of sizeof() function are exactly the same as count() function.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find the average value of an array avg in php. For more information, please follow other related articles on the PHP Chinese website!