Nodral Posted August 8, 2012 Share Posted August 8, 2012 Hi I have the following multidimensional array. array => [0] ([apples]=>5, [pears]=>3, [bananas]=>6) [1] ([apples]=>2, [pears]=>4, [bananas]=>1) [2] ([apples]=>8, [bananas]=>2) How can I iterate through it and produce one array with all the totals added up? eg array => [apples]=>15, [pears]=>7, [bananas]=>9 I've tried googling , but can't seem to find the right thing. Obviously these are example values, the arrays I'm using contain about 40 keys each, therefore this was easier to write / explain. Link to comment https://forums.phpfreaks.com/topic/266805-adding-arrays/ Share on other sites More sharing options...
peipst9lker Posted August 8, 2012 Share Posted August 8, 2012 Replace $fruits with your array. $totals = array(); foreach ($fruits as $fruit) foreach ($fruit as $type => $val) { if (isset($totals[$type])) $totals[$type] += (int)$val; else $totals[$type] = (int)$val; } Link to comment https://forums.phpfreaks.com/topic/266805-adding-arrays/#findComment-1367752 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.