user9055366
user9055366

Reputation:

Undefined array key 1 using PHP

Hello i have warning "Undefined array key 1". I var_dumped array and this is the result. Id like to ask you how can i fix it pls? I tried array_values function but nothing much happened. Im using PHP

array(0) { } 
array(1) { [1]=> array(2) { ["sum"]=> int(26140) ["count"]=> int(1) } } 
array(1) { [1]=> array(2) { ["sum"]=> int(52365) ["count"]=> int(2) } } 
array(1) { [1]=> array(2) { ["sum"]=> int(78510) ["count"]=> int(3) } }

Adding more code. The warning is for last 2 rows

$array_months = array();

  foreach($array as $value) {
    if ($value == null) {
      continue;
    }
    $parts = explode('|', $value);
    $datum = explode ('.', $parts[0]);
    $month_int = (int) $datum[1];
    $value_thousand = str_replace (',', '',$parts[1]);
    $value_int = (int) $value_thousand;
    unset($array_months[0]);
    var_dump($array_months);
    $array_months[$month_int]["sum"] = ($array_months[$month_int]["sum"] + $value_int);
    $array_months[$month_int]["count"] = $array_months[$month_int]["count"]+1;
  }

Upvotes: 1

Views: 5614

Answers (1)

Kazz
Kazz

Reputation: 1180

During the first iteration of your foreach loop and at the assignment line:

$array_months[$month_int]["sum"] = ($array_months[$month_int]["sum"] + $value_int);

the right side is evaluated first and at that moment the $array_months is empty therefore you cannot read the $month_int element of it, because it doesn't exist yet, at any further call its not empty anymore and you don't get the warning multiple times. Since the $month_int in your case is equal to 1 the line unset($array_months[0]); does nothing at all, if you had unset($array_months[1]); or unset($array_months[$month_int]); you would get warning at every iteration.

The actuall fix for your specific case is this:

// check if there is already element/item for $month_int month present in our array
if(isset($array_months[$month_int])){
    // if so we can read previous data and sum/count them
    $array_months[$month_int]["sum"] = ($array_months[$month_int]["sum"] + $value_int);
    $array_months[$month_int]["count"] = $array_months[$month_int]["count"]+1;
}else{
    // when there isn't any record of current month we have to create the first one
    // (there is nothing to sum or count to yet)
    $array_months[$month_int]["sum"] = $value_int;
    $array_months[$month_int]["count"] = 1;
    // since here is no reading of nonexistent element there is no error now
}

Upvotes: 0

Related Questions