PHP sum of two two-dimensional arrays

PHPz
Release: 2023-05-19 18:32:37
Original
981 people have browsed it

In PHP development, it is often necessary to operate on arrays, and summation operations are also common. When we encounter two two-dimensional arrays that need to be summed, we can do it in the following ways.

Method 1: Use a loop to traverse each element and add and sum one by one.

The sample code is as follows:

Copy after login

Output result:

Array ( [0] => Array ( [0] => 8 [1] => 10 [2] => 12 ) [1] => Array ( [0] => 14 [1] => 16 [2] => 18 ) )
Copy after login
Copy after login

Method 2: Use the array_map() function to add and sum each element, which can reduce the amount of code .

The sample code is as follows:

Copy after login

Output result:

Array ( [0] => Array ( [0] => 8 [1] => 10 [2] => 12 ) [1] => Array ( [0] => 14 [1] => 16 [2] => 18 ) )
Copy after login
Copy after login

Method 3: Use the array_reduce() function to sum the two-dimensional array elements.

The sample code is as follows:

Copy after login

Output result:

Array ( [0] => 8 [1] => 10 [2] => 12 [3] => 14 [4] => 16 [5] => 18 )
Copy after login

The above three methods can be selected according to actual needs, and details such as formulas, functions, loops, etc. can be added as needed. Meet different computing needs.

The above is the detailed content of PHP sum of two two-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!