Ivan Topić
Ivan Topić

Reputation: 3185

Unwanted space between php and html

I have this code, the problem is that there is an empty space before each comma.

Name Lastname , (1990.) , Title ...

It should be

Name Lastname, (1990.), Title ...

I need to have data in this format using echo.

ob_start();

...

<?php // DATE  ?>
<?php if(!empty($ref['godina_izdanja'])) :
echo ', (<span class="date">' . $ref['godina_izdanja'] . '</span>.)';
endif; ?>

<?php // TITLE?>
<?php if(!empty($ref['title'])) : 
echo ', <em><span class="title">' . $ref['title'] . '</span></em>';
endif; ?>

Is there something I could do to fix it but to have code readable? I know I can concat everything together but it will become hard to read and mantain

Upvotes: 3

Views: 280

Answers (3)

Ivan
Ivan

Reputation: 40668

If I were I would only use one PHP block

<?php

// DATE
if(!empty($ref['godina_izdanja'])) :
  echo ', (<span class="date">' . $ref['godina_izdanja'] . '</span>.)';
endif;

// TITLE
if(!empty($ref['title'])) : 
  echo ', <em><span class="title">' . $ref['title'] . '</span></em>';
endif;

Upvotes: 0

M K
M K

Reputation: 103

The less Php tags, the less confusion. If you really need to use html in between, try to avoid spaces while going into and out of php tags.

<?php
ob_start();

...

// DATE 
if(!empty($ref['godina_izdanja'])) :
echo ', (<span class="date">' . $ref['godina_izdanja'] . '</span>.)';
endif;

// TITLE
if(!empty($ref['title'])) : 
echo ', <em><span class="title">' . $ref['title'] . '</span></em>';
endif;

?>

Upvotes: 0

Marc B
Marc B

Reputation: 360702

This:

endif; ?>
                            <----right here
<?php // TITLE?>

In a PHP script, ANYTHING that's not within <?php ... ?> tags is treated as output. You have a blank line there, so you're outputting a blank line, which will be rendered as a space by your browser.

There is exactly ZERO point in repeatedly hopping in/out of php mode:

<?php echo 'hi'; ?>
<?php echo 'mom'; ?>

just makes for massively ugly code to read/maintain. Once you're in PHP mode, stay in PHP mode, especially if you're just going to hop in/out:

<?php
echo 'hi';
echo 'mom';
?>

Upvotes: 11

Related Questions