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

青灯夜游
Release: 2023-03-15 22:36:02
Original
2356 people have browsed it

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;
?>
Copy after login

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;
?>
Copy after login

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);
?>
Copy after login

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);
?>
Copy after login

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!

Related labels:
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template