tags:

views:

44

answers:

1

I've been dealing with this for years but it's so nit-picky that I never looked into it. But I have always wondered.

In a PHP template, if I run this:

<p>
<?php echo 'Between "?>" and "</p>" is one linebreak.'; ?>
</p>

<p>
<?php echo 'Between "?>" and "</p>" is one space, then one linebreak.'; ?> 
</p>

<p>
<?php echo 'Between "?>" and "</p>" is two linebreaks.'; ?>

</p>

This is the output:

<p>
Between "?>" and "</p>" is one linebreak.</p>

<p>
Between "?>" and "</p>" is one space, then one linebreak. 
</p>

<p>
Between "?>" and "</p>" is two linebreaks.
</p>

I don't understand this behavior. Why is it ignoring a single line break as if it's not there (like in the first example)?

+5  A: 

The PHP interpreter ignores a line break if it comes immediately after a closing ?>. This is for compatibility with text editors that always add a line break to the last line of a file.

This is briefly mentioned in the PHP manual here and here.

If there's a space before the line break then it's output as normal, it's only if the line break is immediately after that it ignores it.

thomasrutter
Actually, the PHP interpreter actively **removes** the line break. If it'd just *ignore* it this question wouldn't exist. :P `</nitpick>`
deceze
ignores/removes/skips - just a difference in terminology. To clarify, it does not send the line break to output - it treats it as if the line break isn't there.
thomasrutter
Sorry, you just asked me to switch to pedantic: `<?php echo 'Hello World'; ?>\n</p>` → `Hello World</p>` The `</p>` got *ignored*, the `\n` got *removed*. `<?php echo 'Hello World'; ?> \n</p>` → `Hello World \n</p>` The whole ` \n</p>` got *ignored*, nothing got *removed*. :)
deceze
To be pedantic still, PHP is a stream processor, it executes the instructions in the input file to generate output. If some piece of content in the source file doesn't end up in the generated output, that means it got ignored, not that it got removed, because removal implies that PHP somehow modifies the source file, whereas instead it executes it.
Joeri Sebrechts
Seems like text editors should be the ones to conform. Out of curiosity, which text editors do that?
mattalexx
@mattalexx It seems the norm rather than the exception, though many serious programmers' editors list the ability not to add newline at the end of the last line as a feature. vim adds newlines to all lines by default but can be configured to omit it on the last line. Annoyingly it can be impossible to tell if there's a newline on the last line in many text editors as they don't consider the newline to be a "line break" but just an indicator that the line has finished. If you open a file in vim you tell because it goes into a "noeol" mode if the last line has no newline character at the end.
thomasrutter
@thomasrutter Interesting. Well, I wish there were some way around it because it really mucks up my beautiful source. There's always HTML Tidy, I guess.
mattalexx