\n vs. PHP_EOL vs. <br>?
Asked Answered
C

7

43

In most cases, as for one interactive website, when we output multiple lines of contents to web client browser, in my opinion, <BR /> is much more preferable than other two: \n or PHP_EOL.

Else, we need to use "<pre></pre>" to wrap the output content or use nl2br() to insert <BR /> before \n so as the multiple line mark can take effect in HTML. Like following example.

$fruits = array('a'=>'apple', 'b'=>'banana', 'c'=>'cranberry');

// Multiple lines by \n
foreach( $fruits as $key => $value ){
    echo "$key => $value \n" ;
}

// Multiple lines by PHP_EOL
reset( $fruits );
while ( list($key, $value) = each( $fruits ) ){
    echo ("$key => $value" . PHP_EOL);
}

// Multiple lines by <BR />
reset( $fruits );
while ( list($key, $value) = each( $fruits ) ){
    echo ("$key => $value <BR />");
}

Some people believe PHP_EOL is useful when writing data to a file, example a log file. It will create line breaks no matter whatever your platform.

Then, my question is when we use \n? What's the difference between \n and PHP_EOL, and <BR />? Could any body have a big list of each of their pros and cons?

Clishmaclaver answered 27/1, 2014 at 5:15 Comment(3)
This is unrelated, but you can achieve the same effect as your contrived while construction with simply foreach($fruits as $key => $value). That way you also don't have to reset($fruits).Abernon
For the difference between \n and PHP_EOL: de2.php.net/manual/en/reserved.constants.php And <br> is for a whole different context than a line break in a simple text file.Uncanny
(1) "\n" if you're guaranteed on unix/linux, and not in HTML mode (2) PHP_EOL if you're not in HTML mode (3) <br> if you're explicitly and surely outputting HTML (4) if you're not sure whether html is desired or not, using nl2br() later on when you're sure is easier then removing <br> later (5) actually, one should not output anything if the output format is not known yet, which could mean you'd rather return arrays then strings with an uncertain seperator, postponing the decision how to delimit it a string until you do know what to use.Cerebrum
W
45

DOS, Unix, and Mac (pre-OS X and OS X) all use different characters or character combinations to represent "go to the next line."

  • DOS - Uses a CR+LF (that's ASCII 13 followed by an ASCII 10, or \r\n) to represent a new line.

  • Unix - Uses an LF (that's ASCII 10, or \n) to represent a new line.

  • Mac (pre-OS X) - Uses a CR (that's ASCII 13, or \r) to represent a new line.

  • Mac (OS X) - Like Unix, uses an LF to represent a new line.

Therefore, when to use each one depends on what you're going for. If you're writing for a specific platform without the intention of portability, use the character or character combination to break lines that matter to that platform. The purpose of PHP_EOL is to automatically choose the correct character for the platform, so that your new lines are platform-independent.

All of these appear as a single space within a browser as browsers collapse whitespace into a display space for display purposes (unless you're using <pre> as you mentioned, or CSS that changes the behavior of whitespace). This is where <br> comes in, as you've mentioned, which will convert these \n new line characters into <br> so that they provide line breaks in HTML display.

Weightlessness answered 27/1, 2014 at 5:27 Comment(2)
I believe Nick's answer best list out the different line-break character(s) on different platforms, and point out the collapsed white-space when in browser and their solutions. But still thanks kba and m59, their answer still well deserved.Clishmaclaver
U can always use something like sprintf("%c",10); for ascii newline, i belive this will be universally correct on each systemPimentel
E
12

<br>

<br> is only to be used when dividing up text. You may see this used for spacing out elements within an html document, but that is not its purpose, as layout spacing should be achieved with CSS such as margin. Here's a decent use case:

<p>This <br> is <br> some <br> text.</p>

I typically break up my text with linebreaks for readability, so I wouldn't want the linebreaks rendered in the document. That being, the <br> tag is necessary.

CSS whitespace, <pre>

The html element <pre> is an element that, by default, uses CSS rule white-space: pre; so that the document's whitespace is rendered within that element. Normally, only a single space would be rendered regardless of the amount of whitespace in the document. A very good use of this style is for code blocks. If I write a code block, I will naturally space it as I intend and don't particularly care to wrap a <p> tag around each line (that's not semantic anyway) and I don't want to litter my code with <br> either. Even worse, there's the code indentation! whitespace: pre makes a lot of sense here.

<pre>
function foo() {
  //etc
}
</pre>

\r, \n, PHP_EOL

Depending on the platform your php code is running from, you'll need to render a linebreak with \r, \n\, or both \r\n. PHP_EOL will automatically choose for you, so it is the most dynamic approach.

Evans answered 27/1, 2014 at 5:21 Comment(1)
Also PHP_EOL works when you are doing echos from a php file to CMDGramnegative
A
6

It makes no sense to compare a HTML linebreak <br> with actual text linebreaks. <br> is only a linepage in the browser's rendering of a website whereas \n and PHP_EOL are actual, source code linebreaks.

As you mention yourself, PHP_EOL will work regardless of platform and is therefore also preferred over \n. Initially, \n was only the standard linebreak on UNIX, whereas Macintosh used \r and Windows/DOS used a combination of the two: \r\n. When using PHP_EOL, however, you don't have to worry about platform at all.

Nowadays, most systems and editors are tolerant enough to accept whatever linebreak you decide to use, but using the correct one is obviously preferred and most-easily achieved with PHP_EOL, so there's really no reason not to use it.

Abernon answered 27/1, 2014 at 5:21 Comment(1)
Not so when you consider CSS whitespace such as the <pre> tag.Evans
V
4

I have to run scripts on cron and save results to a log file. But sometimes I run the script on my browser. So I do the following test in order to use the correct end of line char:

<?php
$eol = (isset($_SERVER['SHELL'])) ? PHP_EOL : "<br />";
echo "DISCOVER". $eol;
?>
Vitrescent answered 2/10, 2017 at 13:10 Comment(0)
G
1

Very simple answer:

  • use '<br/>'.PHP_EOL inside <body> content or it will make no effect on output page;
  • use PHP_EOL at the end of each line outside <body> content and inside a <script> that is inside body;
  • use \ in the middle of a string that you need to output with separated lines inside.

The rules will output an html page that has its new lines shown to user and, at the same time is readable for developers that try to inspect you html code.

Gilmour answered 17/11, 2021 at 13:40 Comment(0)
S
0

You can create a function with Flavio's code, that always sets the correct newline, no matter if you run it on the shell or in the browser:

<?php
function nl($string) {
  if(isset($_SERVER['SHELL'])) return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
  return nl2br($string);
}


print nl("One\nTwo<br>Three\r\nFour<br />Five
Six" . PHP_EOL);
?>
Sultana answered 7/11, 2017 at 15:45 Comment(0)
K
0

<br>

It was created for HTML designing... <br> will not work in many places until it supports content type is <HTML>

an example1 in mail functions where the content type is text... <br> will not work but /n will work.

more examples where you will see different results.

example 2

<html>
<body>
<script>
document.write("Hello \n World!");
</script>
 </body>
</html>

As document.write writes to the DOM you need to use
for a newline. Relevant MDN docs

example3

txt = "Hello \n World!" ; 
alert(txt);

because alert function is asking a message to be shown to the user it isn't the same as a popup window with HTML in it

/n

is basically common in most of the programming languages for a line break and it will work within most of the platforms. \n and PHP_EOL are actual, source code linebreaks.

The constant PHP_EOL should generally be used for platform-specific output.

Mostly for file output really. Actually, the file functions already transform \n ←→ \r\n on Windows systems unless used in fopen(…, "wb") binary mode. For file input, you should prefer \n however. While most network protocols (HTTP) are supposed to use \r\n, that's not guaranteed.

Therefore it's best to break up on \n and remove any optional \r manually:

example

$lines = array_map("rtrim", explode("\n", $content));

A more robust and terser alternative is using preg_split() and a regexp:

$lines = preg_split("/\R/", $content);

The \R placeholder detects any combination of \r + \n. So would be safest, and even work for Classic MacOS ≤ 9 text files (rarely seen in practice).

Beware that old Macs use \r, this would be a better solution: preg_replace('~\r\n?~', "\n", $str);

PHP_EOL

should be used when writing output such as log files.

It will produce the line break specific to your platform.

it is a constant holding the line break character(s) used by the server platform. In the case of Windows, it's \r\n. On *nix, it's \n. You apparently have a Windows server.

Ki answered 20/2, 2019 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.