You can increment a nonexistent key with +=
. If it does not exist, PHP will automatically create it, with an initial value of null
, which will be cast to zero when you try to add to it. This will generate two notices each time it occurs:
Notice: Undefined offset: x
where x
is the value of $key
and
Notice: Undefined index: total
If you don't care about the notices, go ahead. It will work. If you do care about the notices, you have to check if the key exists before you do anything with it. As you said isset($data[$key]['total'])
will work for this, but really you only need to check isset($data[$key])
since you're only writing to 'total'
for each $key
.
foreach($values as $key => $value){
//modify the key here, so it could be the same as one before
//group by key and accumulate values
$inc = $value - $someothervalue;
if (isset($data[$key])) {
$data[$key]['total'] += $inc;
} else {
$data[$key]['total'] = $inc;
}
}
I would suggest doing it this way because I do care about notices. There are various other questions that discuss this. They're older and probably would be closed as opinion-based by current standards, but some of the opinions there may offer some insight to help you with that decision.