How to create newline in PHP?

To create a newline, PHP provides nl2br() function. It is an in-built function of PHP, which is used to insert the HTML line breaks before all newlines in the string. Although, we can also use PHP newline character \n or \r\n inside the source code to create the newline, but these line breaks will not be visible on the browser. So, the nl2br() is useful here.

The nl2br() function contains these newline characters \n or \r\n which combinely create the newline. Apart from nl2br() function, a html break line tag </br> is used to break the string. The </br> tag should be enclosed in double quotes, e.g., "</br>".

For Example

To create the newline in PHP, let's see the number of examples.

Example 1

Let's take an of example to create the newline with the help of nl2br() function.

snippet
<?php
	echo nl2br("New line will start from here\n in this string\r\n on the browser window");
?>

Output

In this example, we can see that the nl2br() function has contained "\n" and "\r\n" characters in the string for newline. We can see the result of the following program in the below output.

Output
New line will start from here in this string on the browser window

Example 2

snippet
<?php
	echo "One line after\n another line";
	echo " One line after\r\n another line";
?>

Output

In the above example, we can see that after "\n" or "\r\n" character, string did not start from the new line. "\n" and "\r\n" alone are not enough for creating a newline in the string, as the whole string is displayed in a single line.

Output
One line after another line One line after another line
Note
Note: The character "/n" is used in Linux to write a newline whereas in windows "\r\n" is used. For the safe side use the "\r\n" character for creating newline instead.

Example 3

snippet
<?php
	echo "One line after\n another line";
	echo "</br>";
	echo "One line after\r\n another line";
?>

Output

Here, we break the lines using html break line tag "</br>".

Output
One line after another line One line after another line
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents