views:

55

answers:

1

I'm trying to add up two multidimensional arrays, both equally sized, field by field. I.e.:

$sum[4][3] = $a[4][3] + $b[4][3];

Or:

$a = array( array(1, 4), array(3, 2));
$b = array( array(9, 2), array(1, 0));

Should result in:

$sum = array( array(10, 6), array(4, 2));

Is there a more elegant way than foreaching over all the arrays?

+1  A: 

You can use the function array_map() This applies a function to each of the elements in an array ($a in your case) and applies a callback function to those, you can give extra arguments to those functions by supplying another array ($b in your case). The result will be $sum of your example.

The callback function would need to check if the arguments are arrays, if so it would need to do the mapping function again (so its a recursive function) if the arguments aren't an array it needs to add the function.

http://nl3.php.net/manual/en/function.array-map.php

So all in all you'd be off much better doing a nested foreach :)

Thirler