phparrayssummerging-data

Combine and sum two indexed arrays into one flat array


I need a new array combining 2 array with calculation.

$array1 = array(2,5,7,1);

$array2 = array(1,3,2,5);

result array should output

$array3 = array(3,8,9,6);

Is this possible in PHP? I know the array_merge() function combines two array, but how to combine after calculating the sum?

This is possible in C#, but I want to know how I can do it in PHP.


Solution

  • If they are guaranteed to be matched in size then you can use something like this

    $array3 = array();
    
    for($x =0; $x<count($array1); $x++){
         $array3[] = $array1[$x] + $array2[$x];
    }
    

    If the arrays are not guaranteed to be of the same size you can do the following

    $array3 = array();
    $max = max(count($array1), count($array2));
    for($x =0; $x<$max; $x++){
         $array3[] = (isset($array1[$x])?$array1[$x]:0)) + (isset($array2[$x])?$array2[$x]:0));
    }  
    

    With the adoption of PHP 7 and it's null coalesce operator this code becomes much more readable:

    $array3 = array();
    $max = max(count($array1), count($array2));
    for($x =0; $x<$max; $x++){
         $array3[] = ($array1[$x] ?? 0) + ($array2[$x] ?? 0);
    }