1

I have a variable with other content included at each end, but I do not want the extra content to show if the variable is empty. Can I do this without doing a full if-else. Is there anything I can do with the variable to hide all if variable is empty.

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

1 Answer 1

1

You'll need some kind of if-like condition somewhere, there's no built-in shortcut function in PHP that will do this for you (eg. a function that concatenates a bunch of strings if, and only if, all arguments are non-empty).

An alternative method using the ternary operator (just an if-else-like construct on one line):

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

(Btw, the closing parenthesis in your example is arguably in the wrong place.)

If you did find this was a common requirement, then you could perhaps write a function:

/**
 * 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'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.