当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Add new string to variable

问题描述:

What i need to do is this

if (isset($message))

{

$message = $message . $new_message;

}

else

{

$message = $new_message;

}

Is there a simple way to do this with no if ?

I tried

$message .= $new_message;

But when $message is not set, i get Severity Notice Undefined property

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: