1
votes

I have an array like this.

$dataListArray = array(
   array(0,3,0,0,0,0),
   array(0,0,1,0,0,0),
   array(0,0,0,1,0,0),
   array(0,0,0,0,1,0)
);

this data list array can have n number of index and each index array can have n number of data. I am trying to sum the value of each index

$sumArray = array();
foreach ($dataListArray as $subArray) {
    foreach ($subArray as $key => $value) {
        $sumArray[$key]+= $value;
    }
}


// convert sum array as list
$dataList = implode(',', $sumArray);

This is doing sum as I want its output is 0,3,1,1,1,0

but it also giving me notice error

Notice: Undefined offset: 0 in /opt/lampp/htdocs/chart/1.php on line 6

Notice: Undefined offset: 1 in /opt/lampp/htdocs/chart/1.php on line 6

Notice: Undefined offset: 2 in /opt/lampp/htdocs/chart/1.php on line 6

Notice: Undefined offset: 3 in /opt/lampp/htdocs/chart/1.php on line 6

Notice: Undefined offset: 4 in /opt/lampp/htdocs/chart/1.php on line 6

Notice: Undefined offset: 5 in /opt/lampp/htdocs/chart/1.php on line 6

How to get rid of this undefined offset error?

3
You cannot add something to undefined variable. $sumArray[$key] must be defined. - u_mulder
so how to define $sumArray[$key]. - Jai Sharma

3 Answers

3
votes

You have to check if the $key is set by using isset. If not, assign 0.

0 is needed to be initialized since you are doing $sumArray[$key] += $value, if the $sumArray[$key] is not set, You are adding the $value to an undefined.

$dataListArray = array(
   array(0,3,0,0,0,0),
   array(0,0,1,0,0,0),
   array(0,0,0,1,0,0),
   array(0,0,0,0,1,0)
);

$sumArray = array();
foreach ($dataListArray as $subArray) {
    foreach ($subArray as $key => $value) {
        if ( !isset( $sumArray[$key] ) ) $sumArray[$key] = 0; //Check if key exist. Assign 0 if not.
        $sumArray[$key]+= $value;
    }
}

$dataList = implode(',', $sumArray);

This will result to:

0,3,1,1,1,0

Doc: isset()

2
votes

Another possible solution is fill $sumArray with zeros before use it.

$sumArray = array_fill(0, count($dataListArray[0]), 0);
1
votes

Rather than looping over and adding the items up one at a time, you could use array_sum() to add each column up at a time (using array_column() to extract the values to be added).

$dataListArray = array(
    array(0,3,0,0,0,0),
    array(0,0,1,0,0,0),
    array(0,0,0,1,0,0),
    array(0,0,0,0,1,0)
);

$sumArray = array();
foreach ( $dataListArray[0] as $key=>$entry )   {
    $sumArray[$key] = array_sum(array_column($dataListArray, $key));
}
print_r($sumArray);