开发者

Echo placeholder if field is empty

I have an 开发者_如何学Goinput that I'd like to put a placeholder text in, but only if it's respective value is an empty string. The value that should go in the textbox is echoed from a PHP array, but if this value is empty, the placeholder should be echoed instead. At the moment, I've got this code:

<?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?>

sponsorData() just gets stuff from an array; it's only argument is the key. The important bit here is it returns astring.

This code gives odd behaviour; I get stuff like Hello worldAddress Line 1, where Hello world is the user typed text and Address Line 1 is obviously the placeholder. Strangely, the placeholder gets stored into the array on submission.

My question is this: can someone offer a correction of my ternary operator or, if that won't work, tell me to do an inline if statement (blegh)?

Thanks


try the following code:

<?php echo ((sponsorData('address0') == '') ? 'Address Line 1' : 'Other'); ?>

felix


You're running into operator precedence issues. Try:

<?php echo (sponsorData('address0') == '' ? 'Address Line 1' : 'Other'); ?>

(put brackets around the ternary operator statement).


You seem to have this working ok, I don't think the error lies there. Here is how I would do it:

$address0 = sponsorData('address0');

$address0 = !empty($address0) ? $address0 : 'placeholder';


You have to consider that the sponsorData('address0') may have spaces, so you can add the trim function, like this:

<?php echo ((trim(sponsorData('address0')) == '') ? 'Address Line 1' : 'Other'); ?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜