Home > Article > Backend Development > How to sum all array elements in php using loop
php method to use a loop to sum all array elements: 1. Use the for statement to loop through the array, add the elements one by one and sum them, the syntax is "for($i=0;$i
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
Method 1: Use the for statement Loop through the array, add and sum the elements one by one
The for loop will pre-define the variable that controls the number of loops in the for statement, so the for loop statement can follow the known loop The number of times to perform a loop operation is suitable for situations where the number of times the script needs to be run is clearly known (according to the numeric subscript of the index array).
Note: the for statement is only valid for index arrays and cannot traverse associative arrays
<?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; ?>
Description: for loop
The syntax format of the for loop is as follows:
for (初始化语句; 循环条件; 变量更新--自增或自减) { 语句块; }
The for loop statement can be disassembled into 4 parts: the three expressions in ()
and {}## The "statement block" in #, let's analyze it below.
execution flow chart of the for loop statement to understand the execution of the for loop more intuitively. Process:
##Method 2: Use a foreach loop to traverse the array, add and sum the elements one by oneforeach is a statement specially designed for traversing arrays. It is a commonly used method when traversing arrays. It provides great convenience in traversing arrays. After PHP5, you can also traverse objects (foreach can only be applied to arrays and objects).
<?php header('content-type:text/html;charset=utf-8'); $array= array(2,4,6,8,10,12,14,16,18,20); $sum=0; foreach ($array as $value) { $sum+=$value; } var_dump($array); echo '数组所有元素之和:'. $sum; ?>Description: foreach statement
The foreach statement traverses the array and has nothing to do with the array subscript, and can be used for discontinuous indexes Arrays and associative arrays indexed by strings.
The foreach statement has two syntax formats:
foreach ($array as $value){ 语句块; }
Array, assign the value of the current array to $value
in each loop.
foreach ($array as $key => $value){ 语句块; }
array, and in each loop The value of the current array is assigned to $value
, and the key name is assigned to $key
.
Recommended learning: "PHP Video Tutorial
The above is the detailed content of How to sum all array elements in php using loop. For more information, please follow other related articles on the PHP Chinese website!