phpincrement

PHP 8 how to concisely increment dynamically generated variables


PHP 8 raised the Notice to a Warning that an unset variable/array key 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 (in the broadest sense; a variable or an array element value) such as a $_SESSION key 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.


Solution

  • 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.

     $_SESSION['dynamic']['var'] ??= 0;
     $_SESSION['dynamic']['var']++;