Vladimir
Vladimir

Reputation: 1622

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.

Upvotes: 2

Views: 115

Answers (4)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

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.

Upvotes: 3

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10653

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.

Upvotes: 3

Mike Hamilton
Mike Hamilton

Reputation: 1567

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;

Upvotes: 4

bruchowski
bruchowski

Reputation: 5351

You can use ternary operator:

$message = isset($message) ? $message.$new_message : $new_message;

Upvotes: 4

Related Questions