Home >Backend Development >PHP Problem >How to find the sum of elements of an array in php
2 ways to sum: 1. Traverse the array, add the elements and sum, the syntax is "for($i=0;$i
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php calculates array elements Sum method
There are many ways to calculate the sum of array elements in php. This article introduces 2 summation methods,
Method 1. Traversal Array, add and sum the elements one by one
The common way to traverse the array isfor loop(used to index the array) andforeach loop( Both indexed and associative arrays are OK).
Example 1: Sum of for loop
<?php $array= array(1,2,3,4,5,6,7,8,9,10); $sum=0; $len=count($array);//数组长度 for ($i=0; $i < $len; $i++) { $sum+=$array[$i]; } echo '1 + 2 + 3 +...+ 9 + 10 = '. $sum; ?>
Example 2: Sum of foreach loop
<?php header('content-type:text/html;charset=utf-8'); $array= array(1,2,3,4,5,6,7,8,9,10); $sum=0; foreach ($array as $value) { $sum+=$value; } echo '数组所有元素之和:'. $sum; ?>
Method 2: Use array_sum() function
In fact, PHP has a built-in function to find the sum of array elements--array_sum()
<?php header('content-type:text/html;charset=utf-8'); $array= array(1,2,3,4,5,6,7,8,9,10); echo '数组所有元素之和:'. array_sum($array); ?>
Extended knowledge:
PHP not only has a built-in function to find the sum of array elements--array_sum(), but also has a built-in function to find the product of array elements--array_product ()
<?php header('content-type:text/html;charset=utf-8'); $array= array(1,2,3,4,5,6,7,8,9,10); echo '数组元素的乘积:'. array_product($array); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find the sum of elements of an array in php. For more information, please follow other related articles on the PHP Chinese website!