Current Location: Home> Latest Articles> PHP Algorithm Tutorial: How to Multiply Corresponding Elements of Two Arrays

PHP Algorithm Tutorial: How to Multiply Corresponding Elements of Two Arrays

gitbox 2025-07-26

Introduction

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.

Problem Description

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.

Example Demonstrations

$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]

Algorithm Approach

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:

  • Initialize an empty array to store results.
  • Determine the length of the arrays.
  • Loop through the arrays, multiplying the corresponding elements.
  • Store the product in the result array.
  • Return the result array.

Code Implementation

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.

Conclusion

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.