0

I have to perform a big code fix in an old php project. The issue is the following: I have a number statements where the code tries to add integers to non-initialized multimensional arrays, like this:

$array_test['first']['two']['three'] += 10;

But $array_test is declared just like this:

$array_test = array();

This situation gives me a lot of warnings in the project cause this code pattern happens like 16k times.

Is there any way to solve this like adding a statement like this:

if (!isset($array_test['first']['two']['three'])) 
{
         $array_test['first']['two']['three']=0;
}

and then

$array_test['first']['two']['three'] += 10;

But I would like to do it in only one code line (for both statement, the if isset and the increment) in order to make a big and safe replace in my project.

Can someone help me? Thanks and sorry for my english.

  • You're on the right track but your `isset` is looking too far ahead. `$array_test` doesn't even have `['first']` set yet but you're checking several ways down. Everything needs to be init'd step by step. `$array_test['first'] = array();` and then `$array_test['first']['two'] = array();` and so on. Once all levels are declared, then you can init to 0 `$array_test['first']['two']['three']=0;` and your `+=` should work. – dazed-and-confused Jan 26 '23 at 16:37
  • I disagree with the above comment. You do not need to instantiate all parent levels. See my answer. – mickmackusa Jan 27 '23 at 00:47

1 Answers1

1

PHP does not yet (and probably won't ever) have a "null coalescing addition operator.

From PHP7.0, you can avoid the isset() call by null coalescing to 0. Demo

$array_test['first']['two']['three'] = ($array_test['first']['two']['three'] ?? 0) + 10;

If below PHP7 (all the way down to at least PHP4.3), you can use an inline (ternary) condition. Demo

$array_test['first']['two']['three'] = (isset($array_test['first']['two']['three']) ? $array_test['first']['two']['three'] : 0) + 10;
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • Thanks! Is this version compatible also with PHP versions < 7? – Alberto Lancellotti Jan 30 '23 at 08:16
  • The null coalescing operator was born in PHP7. If your boss won't upgrade to a supported version of PHP, them that you are going to quit and find a job where you can develop modern programming skills. – mickmackusa Jan 30 '23 at 09:45