开发者

If a PHP variable is empty, return nothing; and if it's not empty return it with brackets around it

I'm struggling with a form I've built and need some help from you good people out there. I've tried a few techniques using my extremely basic knowledge of arrays and the implode and empty functions but I'm still stuck...

This is a basic version of the HTML:

<input type="radio" name="os_used" class="radio" value="windows" />
<input type="radio" name="os_used" class="radio" value="mac" />
<input type="radio" name="os_used" class="radio" value="other" />
<input type="text" name="os_name" class="text" />

And this is the PHP that uses the above HTML:

$os_used = $_REQUEST["os_used"] ;
$os_name = $_REQUEST["os_name"] ;
$message = "operating system: $os_used ($os_name)" ;

The message is then sent to my email address.

On the form, if the input named 'other' is selected, the 'os_name' text box appears, prompting the user to specify which operating system they use. This is then returned on an email that I'm sent once the form is submitted. The only problem is, 99% of the time, the 'other_os' won't be selected and I'll get this on the email: 'operating system: mac ()' or 'operating system: windows ()'. So I'd only like the brackets to appear if the 'other' radio button is selected, returning something like this 'operating sy开发者_JAVA技巧stem: other (linux)' and the brackets wouldn't be there if 'mac' or 'windows' were selected.

So my thinking is that the brackets would have to be concatenated either side of the $os_name variable and set as a variable in themselves that would only appear on the condition that $os_name had any kind of value entered into it on the form. I'm stumped!

Thanks for your time,

Martin.


Try the code below.

$os_used = $_REQUEST["os_used"] ;
$os_name = $_REQUEST["os_name"] ;

if ($os_name) {
    $message = "operating system: other ($os_name)";
} else {
    $message = "operating system: $os_used";
}


()= Parenthesis. []= Brackets. An important distinction.

$message = "Operating System: $os_used ";
if ($os_name!="") $message.="($os_name)";


You actually want to check that it's not just whitespace, for which you can use trim().

$formatted_os = trim($os_name)? '('.$os_name.')' : '';

Just stick that in after you pull in the $_REQUEST['os_name'] and before the message is created. Optionally instead of using the second variable $formatted_os you could just overwrite $os_name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜