This article provides an in-depth explanation of how to multiply corresponding elements of two arrays using PHP. With detailed analysis and sample code, it will help you easily master this practical algorithm technique.
Given two integer arrays of the same length, return a new array where each element is the product of the elements at the corresponding positions in the original arrays.
$a = [1, 2, 3, 4];
$b = [2, 3, 4, 5];
// Output result: [2, 6, 12, 20]
$a = [4, 6, 2, 1];
$b = [6, 2, 1, 9];
// Output result: [24, 12, 2, 9]
The core idea is to iterate through both arrays by index, multiply the elements at corresponding positions, and save the result into a new array, which is returned at the end.
Steps to implement:
function multiply($arr1, $arr2) {
$res = []; // store result array
$len = count($arr1);
for ($i = 0; $i < $len; $i++) {
$res[$i] = $arr1[$i] * $arr2[$i];
}
return $res;
}
This code is straightforward and easy to understand for all PHP developers.
This article introduced how to multiply corresponding elements of two arrays in PHP, with detailed examples and code demonstration. The method can also be extended to other operations such as addition or subtraction of elements.
Mastering this fundamental algorithm is very helpful for improving PHP programming skills and solving array-related problems. Hope this article is helpful to you.