tags:

views:

1368

answers:

13

I don't really get it: what's the purpose of a new line character?

If I do this:

<?php
echo "This is a test. \n";
echo "This is another test.";
?>

Code results in both sentences being in the same line. Why doesn't the \n causes the second sentence being in second line?

The sentences are each in it's own line, if I do:

<?php
echo "This is a test. <br>";
echo "This is another test.";
?>

But I have also seen people do this:

<?php
echo "This is a test. <br>\n";
echo "This is another test.";
?>

Which essentially results in the same output as the second code snippet. Someone care to explain this?

+38  A: 

The HTML standard treats a line break as just another white space character, which is why the <br> tag exists. Note however a line break will work within a <pre> tag, or an element with the white-space:pre CSS style.

The third example is just to make "pretty" HTML: it makes it easier to "view source" and check it by eye. Otherwise, you have a big long string of HTML.

Paul Dixon
This is far from the only reason for the new line character.
Darryl Hein
In HTML? What is its other purpose?
Chuck
Fourth example is when you output something that is not html. Like plain text. <?php header("content-type: text/plain") ?> or, however it was done... (been a while since I used php)
Svish
+6  A: 

<br> will give you a new line in the user's view; \n will give you a new line in source code, ie. developer's view.

alphadogg
Care to explain what is incorrect?
alphadogg
@tharkun: yes really!
Crescent Fresh
Your distinction of a user's view and developer's view is so very very wrong. The browser's output is of value to both users and developers and the source code is of value to both as well.
Samuel
I think he's learnt his lesson.... (see below)
ck
@Samuel: "so very wrong"? alphadogg's point was not to be taken literally. It's simply an observation about what the browser renders vs the true textual representation.
Crescent Fresh
@ alphadogg, crescentfresh: the distinction isn't to be made between the user's view and the developer's view but but between different output media. a <br /> in a pdf or fulltext-email which is user's view will not help. AND it isn't about VIEW at all new line chars or <br /> tags are not seen.
tharkun
@samuel: How many real end-users of a browser that are not developers look at a page's source code, a.k.a. markup?@tharkun: OK, I get what you are saying. My bad for being loose and informal with the word "view". Should have known better and been more exact.
alphadogg
+8  A: 

as you have observed there are different ways to create a new line.

<br />

this is not a new line character, this is an XHTML tag which means, it works in XHTML. correctly speaking it is not a new line character but the tag makes sure, one is inserted = it forces a line break. closing tag is mandatory.

XHTML specs


<br>

this is a HTML tag which forces a line break. closing tag is prohibited.

HTML 4.1 specs


\n

is an escape sequence for the ASCII new line char LF. A common problem is the use of '\n' when communicating using an Internet protocol that mandates the use of ASCII CR+LF for ending lines. Writing '\n' to a text mode stream works correctly on Windows systems, but produces only LF on Unix, and something completely different on more exotic systems. Using "\r\n" in binary mode is slightly better, as it works on many ASCII-compatible systems, but still fails in the general case. One approach is to use binary mode and specify the numeric values of the control sequence directly, "\x0D\x0A".

read more


PHP_EOL

is a php new line constant which is replaced by the correct system dependent new line.

so the message is, use everything in it's right place.

tharkun
If you cannot understand a question, there is no reason to post an answer.
Geoffrey Chetwood
hey, I was editing this post while the question still had a mess in the examples... the sentence was just there from my first answer.
tharkun
@Tharkun: You should refrain from answering until you have something of value to add then.
Geoffrey Chetwood
I answered and edited and saved during editing, your teacher-like comments are superfluous.
tharkun
I think you meant PHP_EOL
Paul Dixon
@Tharkun: Again, when you post useless (and negative) answers, this is what you get. Not sure why you are upset about it, surely you knew it would be negatively received after reading the FAQ right?
Geoffrey Chetwood
@Paul Dixon: thanks, corrected
tharkun
@Rich B: I don't know what you're talking about, I wasn't posting any useless or negative answers, I was much rather just editing my post and saved it in between.
tharkun
@Tharkun: At least 5 people disagree.
Geoffrey Chetwood
no, 5 ppl have seen my post, when it was by mistake only partial and at that time it didn't make sense.
tharkun
@Tharkun: There is no disputing the revision history: "but maybe after you have corrected your code samples I can be of more help."
Geoffrey Chetwood
what's your aim, Rich B?
tharkun
@tharkun: your first "answer" was pretty lame, ok? However your latest revision is good. I have removed my negative vote in light of this.
Crescent Fresh
yes, my first answer was lame but also a signal for the asker that he would get more as soon as he would correct his code samples.
tharkun
@Tharkun: My 'aim' is to get rid of noise that degrades the signal here. Your first post was definitely just noise.
Geoffrey Chetwood
@Tharkun: If you wish to 'signal' the OP, that is what comments are for.
Geoffrey Chetwood
@tharkun: "this is a xhtml tag which means, it works in html. btw. don't use <br> anymore, only <br /> is correct in the current doctypes because every tag-pair or single tag must have a closing slash."<br /> is not valid in HTML, only XHTML. Learn the difference.
Pesto
:D it seems I'm some kind of red rag today, if it makes you ppl happy, go for it!
tharkun
@Tharkun: Are you disputing being wrong now?
Geoffrey Chetwood
I'm not disputing at all, I'm smiling and I corrected the typo already, I would have thanked Pesto for pointing it out, had he only formulated his feedback in a more constructive way.
tharkun
@tharkun: Funny you say that, that is the same thing I thought about your answer...
Geoffrey Chetwood
@tarkun: You're still wrong, though. While <br /> is correct in XHTML, regular HTML isn't dead. If generating HTML, <br> is the correct tag to use. You're making a blanket statement "don't use <br> anymore" to someone who has little understanding of the subject. Do you think that is wise?
Pesto
I made the difference between xhtml and html clear now.
tharkun
And through it all you have made a further mess. Next edit, try using the shift key.
Geoffrey Chetwood
:D what a nagger!
tharkun
@Tharkun: You seem to be interested in earning respect and/or rep. So either you want to make correct, readable posts that get upvoted or you want to make garbage ones that get downvoted...
Geoffrey Chetwood
whatever you say, Rick B, whatever you say!
tharkun
@Belgariontheking: I am sorry you are offended. Racism should never be tolerated anywhere, including the internet.
Geoffrey Chetwood
what in the world are you guys talking about??? I used the term 'nagger' which is a derivate of the verb 'to nag' which has nothing at all to do with racism.
tharkun
http://www.yourdictionary.com/nag
tharkun
Wow, folks... just wow. +1, because the answer as it is now (which, let's face it, is all that really matters) is better than all the others. :\
Daniel Schaffer
+2  A: 

Your problem is the way html is rendered. If you look in the source code, the first example will have the two lines on separate lines, but the browser does not see line breaks as breaks that should be displayed. This allows you to have a long paragraph in your source:

rghruio grgo rhgior hiorghrg hg rgui  
ghergh ugi rguihg rug hughuigharug 
hruauruig huilugil guiui rui ghruf hf 
uhrguihgui rhguibuihfioefhw8u 
beruvbweuilweru gwui  rgior

That would only wrap as the browser needed it to, allowing it to be easily editable at the right line length, but displayed at any resolution.

ck
+4  A: 

When the html is rendered, only the "<br />" renders the break line. However the markup is much easier to read when "<br />\n" is printed, so that everything is not in one long line.

achinda99
He said <br>, not the <br /> xhtml monstrosity.
recursive
XHTML is a step in the right direction. Closing tags properly and having stricter formats is a good thing. Better, more complete code/markup.
achinda99
+1  A: 

That's because you're creating HTML and view it in a browser, and whitespace is more or less ignored there. Ten spaces don't produce a bigger gap than one space, but that doesn't mean that the space character doesn't work. Try setting the content type to text/plain or look at the HTMLs source to see the effect of the newline.

sth
+1  A: 

The correct XHTML syntax for it would be

echo "This is the test code <br />\n";

The <br /> renders a new line onscreen, the "\n" renders a new line in the source coed

privateace
Not related to the question, although you are correct that example is not valid XHTML.
Darryl Hein
@Darryl: how is it not related to the question?
Crescent Fresh
Last time I checked...When someone asks "What's the purpose of a new line character?" the standard answer would be "To add a new line"However without pointing out the problem to the question which he then delved into. My answer covered what each of the two did. Don't know how that isn't related???
privateace
+2  A: 

HTML does not care about new lines in the source code, you can put it all in one line. It will only interpret <br /> as a new line. You should use an \n to beautify your HTML-output though, but the better way is to not output it with PHP, but to use it in the HTML itself and only embed PHP stuff into it, like this:

<ul id="menu">
    <?php foreach ($menu_items as $item): ?>
    <li>
        <a href="<?= htmlspecialchars($item['link']) ?>" title="<?= htmlspecialchars($item['title']) ?>">
            <?= htmlspecialchars($item['title']) ?>
        </a>
    </li>
    <?php endforeach; ?>
</ul>

That way you won't have to bother with formatting inside PHP, but you automagically have it, by design, in HTML. Also, you seperate Model-logic and View-logic from each other like this and leave the output to your HTTP Server rather than the PHP engine.

Patrick Daryll Glandien
Actually this is considered, in contrast to your opinion, good coding style, because it does not bother PHP with the HTML output. The alternative is *not* deprecated and works very well for templates, as stated above. Of course you should leave the program logic in a model and not in a view
Patrick Daryll Glandien
@Darryl: 1) short_open_tag is not deprecated. 2) although it is not "cross-server", this style of php is perfectly fine in templates, even encouraged. It is clean and fast (does not rely on third party template libraries).
Crescent Fresh
@Darryl Hein the value of old PHP tags hasn't decreased. They have been deprecated though :P
bob esponja
Please refrain from downvoting me if your logic is based on false beliefs caused by lack of research. If you try to rant at me please provide sources for doublechecking your facts
Patrick Daryll Glandien
@bob: short_open_tag is **not deprecated**.
Crescent Fresh
Looks like @Darryl ran off with his comment.
Crescent Fresh
+1  A: 

The new line character is useful otherwise, such as in a PDF. You're correct that the new line character has very little do with HTML as other people have said, it's treated as another while space character. Although it is useful inside the <pre> tag. It can also be used to format the HTML output to make it easier to read. (It's a little annoying to try to find a piece of HTML in a string that's 1000 characters wide.)

The new line character is also useful when storing data in the database. Usually you want to store the data without HTML special characters such as <br /> so that it can be easily used in other formats (again, such as PDF). On output, you want to use the nl2br() function to convert the new lines to <br />s.

Darryl Hein
+3  A: 

\n is code based

<br /> is HTML tag based

There is a clear distinction between the two.

Techboy
+1  A: 

The new line character is is useful for string functions.

For example:

   explode( '\n' , $input );

Would split a string by a new line.

str_replace( '\n' , '<br />' , $input );

Would replace every newline in $input with a br tag.

Also because PHP also has a CLI, \n is useful for formatting:

eg.

echo 'Hello world';

Would, in the CLI, output;

Hello worldphp>

echo 'Hello world' . "\n";

would output;

Hello world
php>

Norse
+1  A: 

Although it also has uses when writing web-based scripts, keep in mind PHP is more than a web engine; it also has a CLI where the br tag is useless.

wdthm
A: 

<br /> is also useless if you're running a script from the command line.

$ php -f file.php
Output <br />$

I know not too many people use PHP from the command line, but it does come up:

file.php:

<?php
print "Output\n";
?>

At the command line:

$ php -f file.php
Output
$
James Socol