PHP eats my newline | Rickard Andersson

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

  1. Posted February 5, 2008 at 19:35 | Permalink

    Clean markup in source code is a must… :P

    Its so much better on the eye.

  2. Gizzmo
    Posted February 24, 2008 at 23:44 | Permalink

    Yes its Very annoying

  3. Posted April 16, 2008 at 05:36 | Permalink

    I’m glad I’m not the only one that noticed PHP does that.

  4. Ben
    Posted May 7, 2008 at 03:58 | Permalink

    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.

  5. Ben
    Posted May 7, 2008 at 04:00 | Permalink

    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.

  6. Posted May 7, 2008 at 09:01 | Permalink

    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.

Post a Comment

Comments are moderated. Your email is never published nor shared.