Reputation: 51
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.
Upvotes: 0
Views: 54
Reputation: 48041
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;
Upvotes: 1