Jimbotron
Jimbotron

Reputation: 83

PHP is removing a newline typed after an echo statement

Consider test.php

OK
here
<?php echo "now"; ?>
what

if you were to run this file, you could expect it to output following:

OK
here
now
what

But it returns

OK
here
nowwhat

What is causing this? Can it be prevented?

P.S.

If you add any character after the line where php code is, even a space, then the newline is retiained.

OK
here
<?php echo "now"; ?>[space]
what

Upvotes: 3

Views: 152

Answers (2)

vidya
vidya

Reputation: 1

Please add a break tag inside echo

OK
here
<?php echo "now <br>"; ?>
what

And your output will be like this:

OK
here
now
what

Upvotes: -1

dpp
dpp

Reputation: 496

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

From php.net

So the "eating" of a newline is expected behavior. The work around as you found is to put a space, or use the above answer and add a \n.

Upvotes: 2

Related Questions