Home >Backend Development >PHP Problem >What is the function of summing and averaging of php arrays?

What is the function of summing and averaging of php arrays?

青灯夜游
青灯夜游Original
2022-06-13 11:51:392484browse

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.

What is the function of summing and averaging of php arrays?

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.

  • ##Use

    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;
    ?>

What is the function of summing and averaging of php arrays?

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.

  • Use array_sum() to calculate the sum of array elements;

  • Use count() to calculate the array length;

  • Use the "array elements and/array length" statement to find the average

  • <?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>";
    ?>

What is the function of summing and averaging of php arrays?

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!

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