Simple Machines Community Forum

Customizing SMF => SMF Coding Discussion => Aiheen aloitti: Biology Forums - elokuu 21, 2013, 12:20:45 IP

Otsikko: Adding an if argument within a string
Kirjoitti: Biology Forums - elokuu 21, 2013, 12:20:45 IP
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?
Otsikko: Re: Adding an if argument within a string
Kirjoitti: Matthew K. - elokuu 21, 2013, 12:41:52 IP
I'd suggest reading up on Ternary Conditions (http://www.addedbytes.com/blog/code/ternary-conditionals/), which is what you're looking for...

tldr;
echo 'Hello ', $context['user']['is_logged'] ? 'Member!' : 'Guest', '!';
Otsikko: Re: Adding an if argument within a string
Kirjoitti: Matthew K. - elokuu 21, 2013, 12:46:49 IP
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']) : '');
Otsikko: Re: Adding an if argument within a string
Kirjoitti: Biology Forums - elokuu 21, 2013, 12:47:43 IP
I know how to use ternary conditions, but just not when variables are being assigned :-\
Otsikko: Re: Adding an if argument within a string
Kirjoitti: Matthew K. - elokuu 21, 2013, 12:48:17 IP
It's the same thing...there's no difference whatsoever.
Otsikko: Re: Adding an if argument within a string
Kirjoitti: Biology Forums - elokuu 21, 2013, 12:51:39 IP
Wonderful, it worked, thanks!
Otsikko: Re: Adding an if argument within a string
Kirjoitti: Matthew K. - elokuu 21, 2013, 12:54:26 IP
You are welcome! Have a good day!