phparraysmultidimensional-arraysumgrouping

Add value to total element which might not exist in an array


I want to do something like this:

foreach($values as $key => $value){
    //modify the key here, so it could be the same as one before

    //group by key and accumulate values
    $data[$key]['total'] += $value - $someothervalue;
}

Is this possible in php? or do i have to check this always first?

isset($data[$key]['total'])

Solution

  • Thanks for all the answers. I went with:

    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]['total']){
            $data[$key]['total'] = 0;
        }
    
        $data[$key]['total'] = += $inc;
    }