PHP 8.0 how to append strings to unknown SESSION variables in a clean concise way without Warnings
Description
PHP version 8.0.15 I have empty error logs because I have notices turned off and I code to the best of my abilities and to best practise as far as practical.
The following code:
<?php
session_start();
$_SESSION['message'] .= "Sorry; That file or location can not be found.";
Resulted in this output:
PHP Warning: Undefined array key "message" in /index.php on line 29
But I expected this output instead:
String is generated without error.
The issue is that $_SESSION is an imported value; I can't force set the value as if a local variable; for fear of overwriting data in the session.
A workaround is
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.";
}
But look at that -- it's 5 extra lines and is a clear failure of DRY programming. With some shorthand encasing it can be reduced down to
$_SESSION['message'] = (array_key_exists('message', $_SESSION)?$_SESSION['message']:"")
."Sorry; That file or location can not be found.";
Which is verbose, hard to read but still on one line, the additional code doesn't DO anything. Apart from hiding the warning message.
Obviously turning off warning messages is not a good idea, and I am left with many, many websites using many thousands of instances of $_SESSION data concatenation that now generate verbose and pointless errors; causing genuine errors harder to find.
So; Can using the array key exist WARNING be relegated to Notice for when string concatenation occurs or for when acted on superglobals (such as $_SESSION) which come into the PHP scope as data from outside and thus can't be set within the script itself.
Thank you.
What's wrong with this?
<?php
session_start();
$_SESSION['message'] ??= '';
$_SESSION['message'] .= "Sorry; That file or location can not be found.";
That is a possible workaround that I hadn't considered. It does still smell of verbose code the need to explicitly set an empty value in order to append to it. But yes, thanks, that's one workaround.
Or $_SESSION['message'] = ($_SESSION['message'] ?? '') . 'Sorry; That file or location can not be found.'; if you want a one-liner.