Home>Article>Backend Development> What is the function to find the average of an array in php?

What is the function to find the average of an array in php?

青灯夜游
青灯夜游 Original
2023-01-12 14:45:07 1273browse

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.

What is the function to find the average of an array in php?

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:
  • 0 - Default. Not counting all elements in a multidimensional array.
  • 1 - Recursively count the number of elements in an array (count all elements in a multidimensional array).

If you are looking for the length of a one-dimensional array, the second parameter$modecan be omitted. If it is a multi-dimensional array, Then the$modeparameter needs to be set to 1.

Step 3: Use the "/" operator to find the average

数组元素和/数组长度

Implementation example:

"; $len=count($arr); echo "数组长度:".$len."
"; $average=$sum/$len; echo "数组平均值:".$average."
"; ?>

What is the function to find the average of an array in php?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn