How to find the sum of two arrays in php

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-06-07 09:54:59
Original
1607 people have browsed it

php method to find the sum of two arrays: 1. Create a PHP sample file; 2. Define two arrays $array1 and $array2 containing integer values; 3. Use "array_map()" The function and the anonymous function of addition merge the two arrays into the $sumArray array; 4. "print_r($sumArray)" output can print the new array.

How to find the sum of two arrays in php

Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.

To sum two PHP arrays, you can use the array_map() function and the added anonymous function.

Here is a PHP example:

$array1 = array(1, 2, 3);
$array2 = array(4, 5, 6);
$sumArray = array_map(function ($a, $b) { return $a + $b; }, $array1, $array2);
print_r($sumArray);
Copy after login

In the above example, we have defined two arrays $array1 and $array2, which contain integer values. We then merge the two arrays into a $sumArray array using the array_map() function and the additive anonymous function.

The anonymous function has two parameters $a and $b, which represent the values ​​​​in $array1 and $array2 at the same index position. This function returns the result of $a $b. The array_map() function uses this anonymous function to process the corresponding elements of all input arrays and returns the new processed array.

The output result is:

Array
(
    [0] => 5
    [1] => 7
    [2] => 9
)
Copy after login

Among them, [0] is the result of $array1[0] $array2[0], [1] is $array1[1] $array2[1] the result, and so on.

The above is the detailed content of How to find the sum of two arrays in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
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!