2

I want to increment a value of an array, which is potentially not existing yet.

$array = [];
$array['nonExistentYet']++; // Notice

Problem

This leads to a NOTICE.

Attempt

I found a way to do this, but its kinda clunky:

$array = [];
$array['nonExistentYet'] = ($array['nonExistentYet'] ?? 0) + 1;

Question

Is there a more human readable/elegant way to do this?

SirPilan
  • 4,649
  • 2
  • 13
  • 26

5 Answers5

2

well i guess a more readable way would be to use if..else as,

$arr = [];
if(array_key_exists('nonExistentYet', $arr)) {
    $arr['nonExistentYet'] += 1;
}
else {
    $arr['nonExistentYet'] = 1;
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
2

If this is used often, you can define a little helper method, which also uses an interesting side effect...

function inc(&$element) {
    $element++;
}
$array = [];
inc($array['nonExistentYet']);
print_r($array);

gives...

Array
(
    [nonExistentYet] => 1
)

with no warning. As you can see the function defines the parameter as &$element, if this value doesn't exist, then it will be created, so the function call itself will create the element and then it will just increment it.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

My standard implementation for this is:

if (isset($array['nonExistentYet']))
   $array['nonExistentYet']++;
else
   $array['nonExistentYet'] = 1;

But this is one of the rarely scenarios where I use the @ operator to suppress warnings, but only if I have full control over the array:

@$array['nonExistentYet']++;

Generally, it is not good to suppress warnings or error messages!

Wiimm
  • 2,971
  • 1
  • 15
  • 25
0

What you ask is a little vague, Either the variable exists and you increment it, or it does not exist in this case you create it. In another case suppose that you want to do it in a for loop, in this case you do not have to worry about the existence of the variable.

-1

One way is ternary operator, which checks if array value exists:

$array['iDoNotExistYet'] = empty($array['iDoNotExistYet']) ? 1 : ++$array['iDoNotExistYet'];

Other one would be just rewriting it to if and else condition.

Ludo
  • 484
  • 2
  • 9
  • I'd rather prefer the if - ternary is super-un-humanreadable :D – SirPilan May 04 '19 at 22:06
  • This will not work. My php assigns always 1 if the value is 1 before. The `x++` increments x to 2, but its previous value `1` is assigned to x. More exact, the result is undefined and implementation dependent, because php can also decide to assign first and then to increment. The keyword for this is `Sequence point`. – Wiimm May 04 '19 at 22:47
  • Just need to replace `$array['iDoNotExistYet']++` by `$array['iDoNotExistYet']+1` - just a typo i guess - but the point was the ternary which is absolutely fine - i just dont like to use it because of extra bainjuice :D – SirPilan May 05 '19 at 09:29
  • I edited to use preincrement, which first increments and then returns value. – Ludo May 05 '19 at 09:54