Home > Article > Backend Development > How to find the sum of two arrays in php
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.
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);
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 )
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!