PHP 8.0 how to append strings to unknown SESSION variables in a clean concise way without Warnings

Viewed 72

Previously code would look like this in PHP 7.4 :

$_SESSION['message'] .= "Sorry; That file or location can not be found.";

Which would append to an existing string or set as contents for a new string. And my erorr logs (with notices turned off) would be beautifully empty.

With PHP 8.0+ now, undefined array elements (amongst other things) are classed as warnings rather than Notices.

PHP Warning: Undefined array key "message" in /index.php on line 29

I understand the conceptual logic behind this Warning but in the instance of the above code it presents the need for a verbose workaround; something like:

if(array_key_exists('message', $_SESSION)){
    $_SESSION['message'] .= "Sorry; That file or location can not be found.";
}
else {
    $_SESSION['message'] = "Sorry; That file or location can not be found.";
}

Or possibly;

$_SESSION['message'] = (array_key_exists('message', $_SESSION)?$_SESSION['message']:"") 
                       ."Sorry; That file or location can not be found.";

Which for thousands of SESSION elements across dozens of websites is really cruddy looking; harder to read and generally a big bloat to avoid Warning messages that seem to serve no purpose.

I don't want to turn warning messages off.

Are there any possible workarounds; such as any way in the php.ini to avoid this trigger for concatenation actions (.=) ? Can we somehow escape system variables (superglobals) or more specifically SESSION data (and POST data perhaps) which it's impossible to know it's value before concatenation.

1 Answers

A more concise workaround can be:

$_SESSION['message'] = ($_SESSION['message'] ?? ''). " string here";

Which is probably as good as it gets.

Related