Joha
Joha

Reputation: 965

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'])

Upvotes: 0

Views: 2260

Answers (4)

Joha
Joha

Reputation: 965

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;
}

Upvotes: 0

Don't Panic
Don't Panic

Reputation: 41810

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.

Upvotes: 0

Geo Halkiadakis
Geo Halkiadakis

Reputation: 380

Php allows adding a NULL value to a number (when used on numeric operations +,-,* handles it as 0), so you do not need to check isset($data[$key]['total']) if you do not mind overwriting it (and from the += operator I think you do not mind).

Upvotes: 0

HugaBuga
HugaBuga

Reputation: 21

If i understand correctly, Can you do it without to check if key exists only in PHP 7 and above

foreach($values as $key => $value)
    $data[$key]['total'] = ($data[$key]['total'] ?? 0) + $value - $someothervalue;;

anyway php allows you to to create new keys like that, but do not forget to disable error reproting in your server to avoid from notices...

Upvotes: 1

Related Questions