PHP 8 raised the Notice to a Warning that an unset variable is worked on.
PHP 7.4:
// Below would create a variable and set it to 0 + 1
// Below would generate a Notice level error.
$_SESSION['dynamic']['var']++;
PHP 8+:
// Below would create a variable and set it to 0 + 1
// Below would create a warning level error that variable does not exist.
$_SESSION['dynamic']['var']++;
Question:
With a dynamically generated variable such as a $_SESSION
value, how can we maintain the current action but prevent the Warning being issued. Hopefully without needing to add loads of extra code bloat.
The only way I can think of is
$_SESSION['dynamic']['var'] = ($_SESSION['dynamic']['var']??0)+1;
Which is a pretty big bloat of code from ++
to ($var??0)+1
.
This seems to entirely negate the whole shortcut of ++
and --
convenient increment/decrement operators. There is no mention of this on the PHP manual pages.
3
Answers
In PHP 8, you can use the null coalescing operator (??) along with the nullsafe operator (?->) to concisely auto-increment dynamically generated variables within an array. This allows you to handle unset variables gracefully without raising warnings.
You can suppress the warning using
@
prefix like this:But relying on default value of undefined variable/index is not exactly a good practice. It might be better to go with longer version you’ve suggested yourself.
If you don’t mind using a reference: