变量添加内容。如果变量为空,则隐藏额外内容

时间:2018-01-19 10:57:41

标签: php

我有一个变量,其中包含其他内容,但我不希望额外的内容显示变量是否为空。如果不做一个完整的if-else,我可以这样做吗?如果变量为空,我可以用变量隐藏所有内容。

<?php if htmlencode($postcode_coveringsRecord['borough']!=""): ?>
<?php echo ' Borough of '.htmlencode($postcode_coveringsRecord['borough'].' area') ?>
<?php endif; ?>

1 个答案:

答案 0 :(得分:1)

你在某处需要某种if条件,PHP中没有内置的快捷功能可以为你做这件事(例如,连接一堆的功能)字符串当且仅当所有参数都是非空的时候)。

使用ternary operator的替代方法(在一行上只是一个if-else类似的构造):

echo (empty($postcode_coveringsRecord['borough']) ? '' : ' Borough of '.htmlencode($postcode_coveringsRecord['borough']).' area');

(顺便说一下,你的例子中的右括号可以说是在错误的地方。)

如果您确实发现这是一个常见的要求,那么您也许可以编写一个函数:

/**
 * Join the passed arguments together.
 * But only if all arguments are not "empty".
 * If any arguments are empty then return an empty string.
 * @param string Strings - Multiple arguments
 * @return string
 */
function joinNonEmptyStr(/* Any number of args */) {
    $result = '';
    $args = func_get_args();
    foreach ($args as $str) {
        // If the argument is empty then abort and return nothing.
        //  - But permit "0" to be a valid string to append
        if (empty($str) && !is_numeric($str)) {
            return '';
        }
        $result .= $str;
    }
    return $result;
}

// Example
echo htmlentities(joinNonEmptyStr(' Borough of ',$postcode_coveringsRecord['borough'],' area'));
相关问题