Home >Backend Development >PHP Problem >How to find the sum of elements of an array in php

How to find the sum of elements of an array in php

青灯夜游
青灯夜游Original
2022-05-07 14:18:332318browse

2 ways to sum: 1. Traverse the array, add the elements and sum, the syntax is "for($i=0;$i

How to find the sum of elements of an array in php

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 &#39;1 + 2 + 3 +...+ 9 + 10 = &#39;. $sum;
?>

How to find the sum of elements of an array in php

Example 2: Sum of foreach loop

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$array= array(1,2,3,4,5,6,7,8,9,10);
$sum=0;
foreach ($array as $value) { 
    $sum+=$value;
} 
echo &#39;数组所有元素之和:&#39;. $sum;
?>

How to find the sum of elements of an array in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$array= array(1,2,3,4,5,6,7,8,9,10);
echo &#39;数组所有元素之和:&#39;. array_sum($array);
?>

How to find the sum of elements of an array in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$array= array(1,2,3,4,5,6,7,8,9,10);
echo &#39;数组元素的乘积:&#39;. array_product($array);
?>

How to find the sum of elements of an array in php

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!

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