Home > Article > Backend Development > Correct way to add arrays in php
In PHP, array is a common data structure with the ability to store and operate large amounts of data. Sometimes we need to add the elements at corresponding positions in the two arrays to get a new array. For example, there are two arrays $a=[1,2,3]$ and $b=[4,5,6]$, we need to get the array $c=[5,7,9]$, that is, at the corresponding position elements are added. Next, I will introduce the method of using php to achieve the correct addition of arrays.
Using loops is a simple way to achieve correct addition of arrays. First, we need to create a new empty array, then iterate through the elements in arrays $a and $b, add them, and store the added result in array $c. The code is as follows:
$a = array(1,2,3); $b = array(4,5,6); $c = array(); for($i = 0; $i < count($a); $i++) { $c[$i] = $a[$i] + $b[$i]; } print_r($c);
The output result is as follows:
Array ( [0] => 5 [1] => 7 [2] => 9 )
Using the array_map function is another way to implement an array The correct way to add. The array_map function can pass each element in the array as a parameter to the specified function and return a new array as the result. Therefore, we can create a custom function that adds the elements at corresponding positions in the two arrays and pass the function as the parameter of the array_map function. The code is as follows:
$a = array(1,2,3); $b = array(4,5,6); function sum($x, $y) { return $x + $y; } $c = array_map("sum", $a, $b); print_r($c);
The output result is the same as the above method.
Finally, we can use the array_reduce function to achieve the correct addition of arrays. The array_reduce function can pass each element in the array to the specified function for operation and return a result value. Therefore, we can create a custom function that adds two numbers and pass this function as an argument to the array_reduce function. The code is as follows:
$a = array(1,2,3); $b = array(4,5,6); function sum($x, $y) { return $x + $y; } $c = array_reduce($a, function($carry, $item) use ($b, $sum) { $carry[] = $sum($item, array_shift($b)); return $carry; }, []); print_r($c);
The output result is the same as the first two methods.
To sum up, the above three methods can all achieve the correct addition of arrays. Which method to choose depends on the specific situation and personal preference. Of course, in addition to these methods, there are other methods to achieve correct addition of arrays, such as using a foreach loop or the array_walk function.
The above is the detailed content of Correct way to add arrays in php. For more information, please follow other related articles on the PHP Chinese website!