• Home
  • How to add two multidimensional array in PHP?

How to add two multidimensional array in PHP?

To add two multidimensional arrays in PHP, you can use a loop to iterate over the elements of each array and perform the addition operation. This can be done using a nested loop structure, where the outer loop iterates over the elements of the first array and the inner loop iterates over the elements of the second array.

Here is an example of how to add two multidimensional arrays in PHP:

$array1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

$array2 = [
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]
];

$result = [];

// Iterate over the elements of the first array
for ($i = 0; $i < count($array1); $i++) {
$result[$i] = [];

// Iterate over the elements of the second array
for ($j = 0; $j < count($array2[$i]); $j++) {
// Perform the addition operation and store the result in the result array
$result[$i][$j] = $array1[$i][$j] + $array2[$i][$j];
}
}

print_r($result);

This code will output the following array:

Array
(
[0] => Array
(
[0] => 11
[1] => 13
[2] => 15
)

[1] => Array
(
[0] => 17
[1] => 19
[2] => 21
)

[2] => Array
(
[0] => 23
[1] => 25
[2] => 27
)
)

The outer loop uses the count() function to iterate over the elements of the first array, and the inner loop uses the count() function to iterate over the elements of the second array. The addition operation is performed on each element of the arrays and the result is stored in the $result array.

It is important to note that the two arrays must have the same dimensions in order for the addition operation to work correctly. If the arrays have different dimensions, you may need to pad the smaller array with additional elements or adjust the loop structure to account for the difference.

You can also use other array functions and techniques to add multidimensional arrays in PHP, such as using the array_map() function or using the + operator to merge the arrays. However, using a loop structure as shown above can be a more flexible and adaptable approach, especially when working with complex or irregularly-shaped arrays.