首页 文章

如果字段为空,则为Echo占位符

提问于
浏览
1

我有一个输入,我想把一个占位符文本,但只有它'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'得到这个代码:

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

sponsorData() 只是从数组中获取内容;它的唯一论点是关键 . 这里重要的是它返回astring .

这段代码给出了奇怪的行为我得到像 Hello worldAddress Line 1 这样的东西,其中 Hello world 是用户输入的文本, Address Line 1 显然是占位符 . 奇怪的是,占位符在提交时存储到数组中 .

我的问题是:有人可以提供我的三元运算符的更正,或者,如果这不起作用,请告诉我做内联 if 语句(blegh)?

谢谢

4 回答

  • 1

    您必须考虑 sponsorData('address0') 可能有空格,因此您可以添加 trim 函数,如下所示:

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

    你似乎有这个工作正常,我不认为错误就在那里 . 我是这样做的:

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

    您遇到了运营商优先级问题 . 尝试:

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

    (在三元运算符声明周围加上括号) .

  • 3

    尝试以下代码:

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

    费利克斯

相关问题