Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of \n and PHP_EOL in PHP?

Tags:

html

php

newline

I'm trying to output a newline character in PHP that gets viewed in a web browser. I can only manage it by using the <br /> tag.

When I use \n, nothing occurs, so what is the benefit of using \n? Also what is the benefit of PHP_EOL? When I concatenate it to a string, just a space is printed not a newline.

like image 943
palAlaa Avatar asked Jul 24 '11 23:07

palAlaa


People also ask

What is the use of Php_eol?

You use PHP_EOL when you want a new line, and you want to be cross-platform. This could be when you are writing files to the filesystem (logs, exports, other). You could use it if you want your generated HTML to be readable.

What is the \n in PHP?

Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.

Does \n work in PHP?

You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.

What is the difference between \n and Br?

<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.


2 Answers

The PHP_EOL define is correct for the platform that you are on. So on windows PHP_EOL is \r\n on MAC it's \r on Linux, it's \n. Whereas <br /> or <br> is the HTML markup for line brake. If you're new to HTML & PHP, it's better to get a grasp of HTML first, then worry about PHP. Or start reading some source code, and run other peoples source code to see how they have done it. It will make you're code better just by copying their style. (Most of the time.)

like image 82
Mark Tomlin Avatar answered Oct 13 '22 22:10

Mark Tomlin


A web browser interprets the output of a PHP program as HTML, so \n and \r\n will not appear to do anything, just like inserting a newline in an HTML file. On the other hand, <br /> makes a new line in the interpreted HTML (hence "line BReak"). Therefore, <br /> will make new lines, whereas \r\n will not do anything.

like image 9
Chris Avatar answered Oct 13 '22 22:10

Chris