Search code examples
phpwhitespacetrim

Cannot get rid of extra space in PHP echo


I'm trying to output a simple text line in a web page. As an example:

Owner, Acme Company

I'm using this bit of PHP to output this line:

<p class="title">
    <?php echo $title ?: ''; ?>
    <?php echo $company ? ", $company" : ''; ?>
</p>

However, when the page is rendered, I get an unwanted space between "Owner" and the comma, like this:

Owner , Acme Company

Both "Owner" and "Acme Company" are in a database and I've checked that their values are clean of any spaces.

I've even tried trim(), like this

<p class="title">
    <?php echo trim($title) ?: ''; ?>
    <?php echo $company ? ", $company" : ''; ?>
</p>

But that didn't trim the whitespace. What am I missing here?


Solution

  • The whitespace is the carriage return and indentation of your markup. You can put the tags together:

    <p class="title">
        <?php echo $title ?: ''; ?><?php echo $company ? ", $company" : ''; ?>
    </p>
    

    Which immediately leads to the idea that they should be one server-side tag instead of two, simply concatenating the values:

    <p class="title">
        <?php echo ($title ?: '') . ($company ? ", $company" : ''); ?>
    </p>