skip to Main Content

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


  1. 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']++;
    
    Login or Signup to reply.
  2. You can suppress the warning using @ prefix like this:

    @$_SESSION['dynamic']['var']++;
    

    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.

    Login or Signup to reply.
  3. If you don’t mind using a reference:

    $v = &$_SESSION['dynamic']['var'];
    $v++;
    $v = &$_SESSION['dynamic2']['var2']; 
    $v += 10;
    unset($v);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search