Home >Backend Development >PHP Problem >How to find the sum of two-dimensional array in php

How to find the sum of two-dimensional array in php

zbt
zbtOriginal
2023-07-12 14:42:552028browse

php method to find the sum of a two-dimensional array: 1. First define a two-dimensional array $matrix; 2. Use two nested foreach loops to traverse each element and accumulate it into the variable $ in sum; 3. Finally, we can output the calculated sum to the screen.

How to find the sum of two-dimensional array in php

The operating environment of this tutorial: windows10 system, php8.1.3 version, DELL G3 computer.

In PHP, we can use a loop to calculate the sum of all elements in a two-dimensional array. The following is a sample code:

//定义一个二维数组
$matrix=array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
//初始化和为0
$sum=0;
//遍历二维数组
foreach($matrixas$row){
foreach($rowas$value){
//将每个元素累加到和上
$sum+=$value;
}
}
//输出结果
echo"二维数组中所有元素的和为:".$sum;
?>

1. In the above code, we first define a two-dimensional array $matrix. The array contains 3 sub-arrays, each of which has 3 integer elements.

2. Then, we use two nested foreach Loop through each element and accumulate it into the variable $sum

3. Finally, we output the calculated sum to the screen.

The output result of the above example is: the sum of all elements in the two-dimensional array is: 45.

It should be noted that in actual applications, we may need to first determine whether the dimensions and elements of the two-dimensional array meet the requirements, and perform safe processing of the array, such as null checking, checking the legality of the input data, etc. .

The above is the detailed content of How to find the sum of two-dimensional 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