4

I was studying php with tutorial. I recognized that in php
is sometimes use like this

echo $myString."<br />"

Suddenly, there came another in the tutorial "\n" and I got confused. Can I use it just like I use

<br />

?

So like this?

echo $mySting."\n"

Is it like a html tag? What's the difference between

<br /> and \n?
Kim
  • 79
  • 1
  • 1
  • 4

3 Answers3

8

<br /> is a HTML line-break, whereas \n is a newline character in the source code.

In other words, <br /> will make a new line when you view the page as rendered HTML, whereas \n will make a new line when you view the source code.

Alternatively, if you're outputting to a console rather than somewhere that will be rendered by a web browser then \n will create a newline in the console output.

thexacre
  • 702
  • 4
  • 9
4

\n is a new line character (a literal new line as you would type in your code).

$newline = "
";

var_dump($newline === "\n");
// true

You can also use the PHP constant PHP_EOL (end of line). Note, that '\n' will render \n as a literal string; you must use double quotes to have it rendered as a new line character. Also note, that my above example may actually output false..since sometimes new lines are rendered as \r\n.


<br /> is an HTML element for a line break. This will show up as a new line when HTML is rendered in a browser.


The only time that \n will show up as a rendered line break in HTML, is when it is within a <pre> (pre-formatted text) element. Otherwise it would be the same as just formatting/indenting your HTML code:

<?php
echo "<html>\n\t<body>\n\t\tHello World!\n\t</body>\n</html>";

Outputs:

<html>
    <body>
        Hello World!
    </body>
</html>
Community
  • 1
  • 1
Sam
  • 20,096
  • 2
  • 45
  • 71
4

\n is a new line feed within the context of plain text, while <br /> is line break within the context of HTML.

HTML can interpret \n when using preformatted blocks (e.g. <pre>), but it does not by default, and should not unless there is a specific use case (like when quoting, citing poetry, or showing code).

<br /> should never be used to separate text that should otherwise be treated as a paragraph, heading or other group of text.

zamnuts
  • 9,492
  • 3
  • 39
  • 46