What i need to do is this
$message = $message . $new_message;
$message = $new_message;
Is there a simple way to do this with no
$message .= $new_message;
$message is not set, i get Severity Notice
The reason i need to do this is i show errors/messages with
$message in views and if i simply do
$message = $new_message; older errors/messages are gone.
Any help/method is appreciated.
You can use ternary operator:
$message = isset($message) ? $message.$new_message : $new_message;
There's no way to do this in PHP without some sort of conditional statement. I think the if/else is readable but if you want something more concise you can try a ternary operator like this:
$message = isset($message) ? $message . $new_message : $new_message;
A simple way to go with ternary operator:-
$message = (isset($message) && $message!='') ? $message.$new_message : $new_message;
Note:- you can remove empty check condition, but its for your betterment.
A conditional statement (either what is in the question or a ternary operator as shown in other answers) is the right way to go.
However, in this case you might want to just tell PHP to ignore the warning, and not throw it at all. You can achieve that using the
@ symbol, as such:
@$message .= $new_message;
This is not a best practice, but I do believe it's best to know it for completeness. The above snippet will not emit any error or warning at all, at your request.