News:

SMF 2.1.6 has been released! Take it for a spin! Read more.

Main Menu

Adding an if argument within a string

Started by Biology Forums, August 21, 2013, 12:20:45 PM

Previous topic - Next topic

Biology Forums

Here's the code:

$immessage .= $txt['visual_received_warning'] .
"\n\n$scripturl?topic=$_REQUEST[topic].msg$_REQUEST[msg]#msg$_REQUEST[msg]"

. "\n\nThe Reason: ". $message ."\n\nCurrent Level: ". $_REQUEST['level'];


I'd like to add, within this string, if(empty($message)) ? '' : '\n\nThe Reason: ". $message .'

How do I do this?

Matthew K.

I'd suggest reading up on Ternary Conditions, which is what you're looking for...

tldr;
echo 'Hello ', $context['user']['is_logged'] ? 'Member!' : 'Guest', '!';

Matthew K.

Now that I actually take a second to look at your code...

The Easiest Way:
$immessage .= $txt['visual_received_warning'] . "\n\n" . $scripturl . '?topic=' . $_REQUEST['topic'] . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg'];
if (!empty($message))
$immessage .= "\n\n" . 'The Reason: ' . $message . "\n\n" . 'Current Level: ' . $_REQUEST['level'];

Since you're just adding something else to the string if a condition is evaluated as true, you can just concatenate it onto the end of the string.

More Difficult Way:
$immessage .= $txt['visual_received_warning'] . "\n\n" . $scripturl . '?topic=' . $_REQUEST['topic'] . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg'] . (!empty($message) ? ("\n\n" . 'The Reason: ' . $message . "\n\n" . 'Current Level: ' . $_REQUEST['level']) : '');

Biology Forums

I know how to use ternary conditions, but just not when variables are being assigned :-\

Matthew K.

It's the same thing...there's no difference whatsoever.


Matthew K.


Advertisement: