justinhj
justinhj

Reputation: 11316

Increment or create a numeric value in an array

I want to create or increment a value for a key in an array. So for example if I have a key 'money' I can increment it in the array by a set value, or create it if it doesn't exist yet. Currently I'm doing this which seems a long way of going about it.

if(array_key_exists("money", $account_array)) {
    $account_array["money"] = $account_array["money"] + $increase;
}
else {
    $account_array["money"] = $increase;
}

Upvotes: 0

Views: 156

Answers (4)

ComFreek
ComFreek

Reputation: 29434

if(!isset($account_array['money'])) {
    $account_array['money'] = 0;
}

$account_array["money"] += $increase;
  • use isset() if you can be sure that the array does either contain a non-null value or that it does not contain key at all.

  • use a += b which would be equivalent to a = a + b

Upvotes: 2

Pevara
Pevara

Reputation: 14310

you could shorten the synatx a bit, but basically your method is correct

array_key_exists('money', $account_array) 
    ? $account_array["money"] += $increase 
    : $account_array["money"] = $increase;

Upvotes: 0

anon
anon

Reputation:

You can a ternary statement and compress it to a single line, but this compromises readability:

$account_array["money"] = (array_key_exists("money", $account_array)) ? 
$account_array["money"] + $increase : $increase;

See it live!

Upvotes: 0

Victor
Victor

Reputation: 5353

What about

    array_key_exists("money", $account_array) ? $account_array["money"] += $increase : $account_array["money"] = $increase;

Upvotes: 1

Related Questions