PHP eats my newline
Have a look at the PHP manual page on Instruction separation. In particular:
The closing tag for the block will include the immediately trailing newline if one is present.
What this means is that a newline character directly after the PHP end tag will be stripped out. Have a look at this code.
Line 1
<?php echo 'Line 2'; ?>
Line 3
Looking at it, one would expect the output to be three lines. However, due to the aforementioned oddity, the output is:
Line 1
Line 2Line 3
This might not be the end of the world for most people because it hardly ever has any impact on the actual appearance of your pages. However, for someone like me, it’s very annoying. You see, I am extremely anal when it comes to the appearance of markup in my scripts. If I see a line of markup that isn’t properly indented or if I see missing or redundant whitespace, my programmers OCD kicks in and I start adding “\t” and “\n” all over the code.
The manual doesn’t mention anything about the reasoning behind the behavior and I haven’t been able to find anything online on the subject. The only reason I can think of is that the behavior is there to prevent a single newlines at the very end of scripts. This in turn to prevent “Headers already sent” errors when sending HTTP headers (for example cookies). Still, I think it hurts more than it helps.

6 comments
Clean markup in source code is a must… :P
Its so much better on the eye.
Yes its Very annoying
I’m glad I’m not the only one that noticed PHP does that.
I like the way the end of a PHP block includes the newline directly after it; what if you wanted to loop within the block:
Line Before
<?php
for ($i=0; $i
Line After
Then it works as expected, rather than having a blank line between “Internal Line 9″ and “Line After”… If it didn’t gobble the newline then you’d need:
Line After
Which is even worse, IMHO.
Try again:
Line Before
<?php
for ($i=0; $i<10; $i++)
echo “Internal Line $i\n”;
?>
Line After
Then it works as expected, rather than having a blank line between “Internal Line 9″ and “Line After”… If it didn’t gobble the newline then you’d need:
<?php
…
?>Line After
Which is even worse, IMHO.
I disagree. In my opinion, if there are two newlines, it should output two newlines. Anything else is “magic” and that’s something we want to avoid as much as possible.