Is there a clean way to accomplish the following without writing an ugly bunch of for loops and logic blocks?

<?php

//INPUT
$aRaw = [
	['in' => [1,2,3], 'out' =>[4,5,6]],
	['in' => [7,8,9], 'out' =>[1,2,3]]
];

//DESIRED OUTPUT
$aSum = ['in' => [8,10,12], 'out' =>[5,7,9]];

?>

$aN is a factor, so there may only be one set in $aRaw or there may be 5+

Thank you =)

    I mean, this works, but triple nested foreach loops makes my skin crawl AND throws undefined offsets where $sum is being filled:

    <?php
    //INPUT
    $aRaw = [
    	['in' => [1,2,3], 'out' =>[4,5,6]],
    	['in' => [7,8,9], 'out' =>[1,2,3]]
    	];
    
    $sum = [];
    foreach($aRaw as $aSet) {
    	foreach($aSet as $k => $kv) {
    		$i = 0;
    		foreach($kv as $v) {
    			$sum[$k][$i] += $v;
    			$i++;
    		}
    	}
    }
    
    print_r($sum);
    ?>
    
    Array
    (
        [in] => Array
            (
                [0] => 8
                [1] => 10
                [2] => 12
            )
    
    [out] => Array
        (
            [0] => 5
            [1] => 7
            [2] => 9
        )
    
    )
    

    Gotta be a better way

      So far everything else I think of ends up more complicated. 🙁

        Change:

        // from this
        $sum = []; 
        
        // to this
        $sum = [array_fill(0,3,0), array_fill(0,3,0)];
        

        And that will remove the notices from it being undefined. Everything is going to involve nested loops unfortunately, even if you us array_map and friends, you're just moving the loop to inside the C function.

          Thanks guys... Added in @'s suggestion and it's workin'

          Was hoping for a more elegant way but needs vs wants

            Write a Reply...