PHP Question

PHP : How to get sum of multiple array with dynamic array name

I have an arrays with dynamic name. My array could be more than 3, depends and array variable should be unique

$loopThrice = 3;
$getSum = 0;
$total = array();

$array0 = array(5, 10, 15, 20, 25, 30);
$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(2, 6, 8, 10, 12, 14);

for($a=0; $a < $loopThrice; $a++){ // loop 3x to get unique array name

foreach (${'array'.$a} as $key => $value) { // $array0, $array1, $array2,
//Right here is my problem, I'm not sure if this the correct way to get the sum of $array0,1,2

//get the sum of array0,1,2 -- newarray(8, 18, 26, 34, 42, 50)
$getSum +=

//store newarray
array_push($total, $getSum);


}
}


I need to get an output like this

print_r(total);

Array (
[0] => 8
[1] => 18
[2] => 26
[3] => 34
[4] => 43
[5] => 50
)

Answer

Why aren't you using a multidimensional array?

$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25, 30);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10, 12, 14);

In this case you will have an array of arrays:

Array
(
[0] => Array
    (
        [0] => 5
        [1] => 10
        [2] => 15
        [3] => 20
        [4] => 25
        [5] => 30
    )

[1] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
        [5] => 6
    )

[2] => Array
    (
        [0] => 2
        [1] => 6
        [2] => 8
        [3] => 10
        [4] => 12
        [5] => 14
    )
)

You can go with nested for loops:

$sumArray = array();
$arrayCount = count($array);
$elementCount = 0;

foreach($array as $subarray)
{
    $count = count($subarray);
    $elementCount = $elementCount < $count ? $count : $elementCount;
}

for($i = 0; $i < $elementCount; $i++)
{
    $sumArray[$i] = 0;

    for($j = 0; $j < $arrayCount; $j++)
    {
        $sumArray[$i] += $array[$j][$i];
    }
}

print_r($sumArray);

The output is

Array
(
    [0] => 8
    [1] => 18
    [2] => 26
    [3] => 34
    [4] => 42
    [5] => 50
)

Now, if you have a disproportioned sub-arrays (i.e. different count of elements in each sub-array), you will still get some sort of result, as missing elements will be assumed to be 0. So, with the input of:

$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10);

You will still get the result:

Array
(
    [0] => 8
    [1] => 18
    [2] => 26
    [3] => 34
    [4] => 30
    [5] => 6
)